如何通过reflection检查属性是否为虚拟?

给定一个对象,我该如何判断该对象是否具有虚拟属性?

var entity = repository.GetByID(entityId); 

我试过看:

 PropertyInfo[] properties = entity.GetType().GetProperties(); 

但无法辨别出任何属性是否表示虚拟。

 PropertyInfo[] properties = entity.GetType().GetProperties() .Where(p => p.GetMethod.IsVirtual).ToArray(); 

或者,对于.NET 4及更低版本:

 PropertyInfo[] properties = entity.GetType().GetProperties() .Where(p => p.GetGetMethod().IsVirtual).ToArray(); 

这将获得公共虚拟属性的列表。

它不适用于只写属性。 如果需要,可以手动检查CanReadCanWrite ,并阅读相应的方法。

例如:

 PropertyInfo[] properties = entity.GetType().GetProperties() .Where(p => (p.CanRead ? p.GetMethod : p.SetMethod).IsVirtual).ToArray(); 

你也可以抓住第一个访问者:

 PropertyInfo[] properties = entity.GetType().GetProperties() .Where(p => p.GetAccessors()[0].IsVirtual).ToArray(); 

仅检查属性的访问者的IsVirtual将为您提供未在类中声明为virtual接口属性。 如果“虚拟属性”是指您可以在派生类中覆盖的属性,则还应检查IsFinal (已密封):

 var accessor = typeof(MyType).GetProperty("MyProp").GetAccessors()[0]; var isVirtual = accessor.IsVirtual && ! accessor.IsFinal; 

检查此示例应用:

 using System; namespace VirtualPropertyReflection { interface I { int P1 { get; set; } int P2 { get; set; } } class A : I { public int P1 { get; set; } public virtual int P2 { get; set; } static void Main() { var p1accessor = typeof(A).GetProperty("P1").GetAccessors()[0]; Console.WriteLine(p1accessor.IsVirtual); // True Console.WriteLine(p1accessor.IsFinal); // True var p2accessor = typeof(A).GetProperty("P2").GetAccessors()[0]; Console.WriteLine(p2accessor.IsVirtual); // True Console.WriteLine(p2accessor.IsFinal); // False } } } 

看到这个答案 。

试试吧

 typeof(YourClass).GetProperty("YouProperty").GetGetMethod().IsVirtual; 

使用GetAccessors方法,例如第一个属性:

获取访问者:

 properties[0].GetAccessors()[0].IsVirtual 

设置访问者:

 properties[0].GetAccessors()[1].IsVirtual 

这有点棘手,因为属性可以是只读,只写或读/写。 因此,您需要检查两个基本方法是否为虚拟,如下所示:

 PropertyInfo pi = ... var isVirtual = (pi.CanRead && pi.GetMethod.IsVirtual) || (pi.CanWrite && pi.SetMethod.IsVirtual);