繁体   English   中英

使用反射获取特定类型的属性列表

[英]Getting the list of proprieties of a specific type using reflection

我想获取特定类型对象的属性列表,我已经使用了此静态方法来完成这项工作。

例如:A类具有3个bool属性,调用GetPropertiesList <bool>(aInstance); 将返回具有所有布尔返回属性的列表。

可以吗?还是我在这里重新发明轮子?

    public static List<T> GetPropertiesList<T>(object obj)
    {
        var propList = new List<T>();
        PropertyInfo[] properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
        //search
        foreach (PropertyInfo prop in properties)
        {
            if (prop.PropertyType != typeof(T)) { continue; }

            else
            {
                //Add to list
                var foundProp = (T)prop.GetValue(obj, null);
                propList.Add(foundProp);
            }
        }
        return propList;
    }

如果PropertyTypeT的子类,则此方法不起作用。 例如,如果您有此类:

class SomeImages{
    public Bitmap Img1{get;set;}
    public Image Img2{get;set;}
}

然后, GetProperties<Image>(instanceOfSomeImages)将仅返回Img2。 同样, GetProperties<Bitmap>(instanceOfSomeImages)将仅返回Img1。

而不是像prop.PropertyType != typeof(T)那样进行检查,您可能应该做typeof(T).IsAssignableFrom(prop.PropertyType)

最后, if(not isGood){continue;}else{doSomething;}if(not isGood){continue;}else{doSomething;}有点草率。 if(isGood){doSomething;}操作要简单得多。

您可以使用LINQ来缩短查询,例如:

obj.GetType()
   .GetProperties(BindingFlags.Public | BindingFlags.Instance)
   .Where(p=>typeof(T).IsAssignableFrom(p.PropertyType))
   .Select(p=>(T)p.GetValue(obj,null))
   .ToList();

更新

您还可以检查Type.FindMembers方法,该方法接受一个MemberFilter委托来过滤它返回的成员,但是我认为这不会更简单或更快速。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM