对不起,我正在查找文档中的System.Type类型和PropertyInfo类型,但我似乎无法找到我需要的东西.
如何判断属性(或方法或任何其他成员)是否virtual在其声明类中声明?
例如
class Cat
{
public string Name { get; set; }
public virtual int Age { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
如何判断Age财产是否被宣布virtual?
Dar*_*rov 66
您可以使用IsVirtual属性:
var isVirtual = typeof(Cat).GetProperty("Age").GetGetMethod().IsVirtual;
Run Code Online (Sandbox Code Playgroud)
cdh*_*wie 21
从技术上讲,属性不是虚拟的 - 它们的访问者是.试试这个:
typeof(Cat).GetProperty("Age").GetAccessors()[0].IsVirtual
Run Code Online (Sandbox Code Playgroud)
如果需要,可以使用如下所示的扩展方法来确定属性是否为虚拟:
public static bool? IsVirtual(this PropertyInfo self)
{
if (self == null)
throw new ArgumentNullException("self");
bool? found = null;
foreach (MethodInfo method in self.GetAccessors()) {
if (found.HasValue) {
if (found.Value != method.IsVirtual)
return null;
} else {
found = method.IsVirtual;
}
}
return found;
}
Run Code Online (Sandbox Code Playgroud)
如果它返回null,则该属性没有访问者(应该永远不会发生)或者所有属性访问者都没有相同的虚拟状态 - 至少有一个是,而一个不是虚拟的.