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

时间:2012-09-06 18:10:10

标签: c# reflection virtual

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

var entity = repository.GetByID(entityId);

我试着查看:

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

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

6 个答案:

答案 0 :(得分:33)

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();

答案 1 :(得分:14)

仅检查属性的访问者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
        }
    }
}

请参阅this answer

答案 2 :(得分:8)

尝试

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

答案 3 :(得分:5)

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

获取访问者:

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

设置访问者:

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

答案 4 :(得分:3)

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

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

答案 5 :(得分:0)

仅IsVirtual不适用于我。告诉我,我所有的非虚拟非空属性都是虚拟的。我不得不结合使用IsFinal和IsVirtual

这就是我最终得到的:

PropertyInfo[] nonVirtualProperties = myType.GetProperties().Where(x => x.GetAccessors()[0].IsFinal || !x.GetAccessors()[0].IsVirtual).ToArray();

PropertyInfo[] virtualProperties = myType.GetProperties().Where(x => !x.GetAccessors()[0].IsFinal && x.GetAccessors()[0].IsVirtual).ToArray();
相关问题