gpt4 book ai didi

c# - 为什么从接口(interface)继承的属性会变成虚拟的?

转载 作者:IT王子 更新时间:2023-10-29 03:59:06 25 4
gpt4 key购买 nike

假设我有一个接口(interface)和两个类,其中一个类实现了这个接口(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; }
}

AAA2 类中,属性 F1 是从接口(interface) IAAA“继承”(我不确定),然后我使用反射来检查一个属性是否是虚拟的:

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");
}

输出是:

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

有什么原因吗?

最佳答案

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

如果您需要确定此方法是否可重写,那么检查 IsVirtual 是不够的,您还需要检查 IsFinal 是否为 false。

这是执行此检查的扩展方法:

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

关于c# - 为什么从接口(interface)继承的属性会变成虚拟的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53492538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com