如何使用属性获取所有属性ReadOnly(true)使用Refection [英] How to get all the Properties with Attributes ReadOnly(true) Using Refection

查看:91
本文介绍了如何使用属性获取所有属性ReadOnly(true)使用Refection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个班级:

Hi,
I have a Class :

class Foo
    {
        [ReadOnly(true)]
        public string Bar { get; set; }

        [ReadOnly(false)]
        public string Que { get; set; }
    }







想要获得具有ReadOnly属性的所有属性( true)

attribs =(来自p in typeof(Foo).GetProperties()

let attrs = property.GetCustomAttributes(typeof(Foo),true)



select p.Attributes).ToList();



此代码不起作用。



任何建议Plz!




Want to get the All the properties which has attributes with ReadOnly(true)
attribs = (from p in typeof(Foo).GetProperties()
let attrs = property.GetCustomAttributes(typeof(Foo), true)

select p.Attributes).ToList();

This code doesnot work.

Any Suggestion Plz!

推荐答案

首先,获取所有属性:http://msdn.microsoft.com/en-us/library/kyaxdd3x.aspx [ ^ ]。



然后为每个房产返回信息,获取所有自定义属性: http://msdn.microsoft.com/en-us/library/ dwc6ew1d.aspx [ ^ ]。



调用上面引用的方法的第一个参数应该是 System.ComponentModel.ReadOnlyAttribute 的类型。它将确保您只获得此类型的属性,因此您可以将每个属性(如果有)强制转换为此类,然后检查其属性 IsReadOnly

http://msdn.microsoft.com/en-us /library/system.componentmodel.readonlyattribute.isreadonly.aspx [ ^ ]。



这样,您将遍历所有属性并收集满足您的所有属性某些收藏中的标准。



-SA
First, get all properties: http://msdn.microsoft.com/en-us/library/kyaxdd3x.aspx[^].

Then for each property info returned, get all custom attributes: http://msdn.microsoft.com/en-us/library/dwc6ew1d.aspx[^].

First parameter in the call to the method referenced above should be the type of System.ComponentModel.ReadOnlyAttribute. It will ensure that you got only the attributes of this type, so you can cast each attribute (if any) to this class and then check up its property IsReadOnly:
http://msdn.microsoft.com/en-us/library/system.componentmodel.readonlyattribute.isreadonly.aspx[^].

This way, you will traverse all the properties and can collect all properties which meet your criterion in some collection.

—SA


这篇关于如何使用属性获取所有属性ReadOnly(true)使用Refection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆