获取Public propertyinfo的正确方法是什么?

时间:2013-12-28 21:13:48

标签: c# reflection

以下是最便捷的方式吗?

type.GetProperties().Where(pinfo=> pinfo.CanRead).ToArray();

我想做的就是忽略以下

private object prop {get;set;}
protected object prop {get;set;}

但不是

public object prop {get;set;}
public object prop {get;private set;}

2 个答案:

答案 0 :(得分:3)

有一个重载需要BindingFlags作为参数:Type.GetProperties Method (BindingFlags)

type.GetProperties(BindingFlags.Public | BindingFlags.Instance)

快速测试表明它可以准确地返回您所需的内容:

public class TestClass
{
    private object prop1 { get; set; }
    protected object prop2 { get; set; }

    public object prop3 { get; set; }
    public object prop4 { get; private set; }
}
var prop = typeof(TestClass).GetProperties(BindingFlags.Instance | BindingFlags.Public);

返回2个元素:prop3prop4属性。

答案 1 :(得分:1)

不仅仅是GetProperties吗?默认情况下,您只会获得公共属性。

var properties = type.GetProperties();

注意:这也包括静态属性和只写属性,但我相信没有人设计一个只有set accessor的属性。