Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

c# - Why does a property inherited from an interface become virtual?

Say I have one interface and two classes, and one of the classes implement this interface:

interface IAAA
{
    int F1 { get; set; }
}

class AAA1
{
    public int F1 { get; set; }
    public int F2 { get; set; }
}

class AAA2 : IAAA
{
    public int F1 { get; set; }
    public int F2 { get; set; }
}

In class AAA2, property F1 is 'inherited' (I'm not sure) from interface IAAA, then I use reflection to check whether a property is virtual:

Console.WriteLine("AAA1 which does not implement IAAA");
foreach (var prop in typeof(AAA1).GetProperties())
{
    var virtualOrNot = prop.GetGetMethod().IsVirtual ? "" : " not";
    Console.WriteLine($@"{prop.Name} is{virtualOrNot} virtual");
}

Console.WriteLine("AAA2 which implements IAAA");
foreach (var prop in typeof(AAA2).GetProperties())
{
    var virtualOrNot = prop.GetGetMethod().IsVirtual ? "" : " not";
    Console.WriteLine($"{prop.Name} is{virtualOrNot} virtual");
}

The output is:

AAA1 which does not implement IAAA
F1 is not virtual
F2 is not virtual
AAA2 which implements IAAA
F1 is virtual
F2 is not virtual

Any reason for this?

question from:https://stackoverflow.com/questions/53492538/why-does-a-property-inherited-from-an-interface-become-virtual

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As from remarks section of MS docs:

A virtual member may reference instance data in a class and must be referenced through an instance of the class... The common language runtime requires that all methods that implement interface members must be marked as virtual; therefore, the compiler marks the method virtual final

If you need to determine whether this method is overridable then checking IsVirtual is not enough and you need to also check that IsFinal is false.

Here is an extension method that do this check:

public static bool IsOverridable(this MethodInfo method)
    => method.IsVirtual && !method.IsFinal;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...