2011-09-26 16 views
4

過濾掉受保護的setters我想反映一個類型,並獲得公共setter的屬性。這似乎不適合我。在下面的示例LinqPad腳本中,'Id'和'InternalId'與'Hello'一起返回。我能做些什麼來濾除它們?當type.GetProperties()

void Main() 
{ 
    typeof(X).GetProperties(BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance) 
    .Select (x => x.Name).Dump(); 
} 

public class X 
{ 
    public virtual int Id { get; protected set;} 
    public virtual int InternalId { get; protected internal set;} 
    public virtual string Hello { get; set;} 
} 

回答

4

可以使用GetSetMethod()確定二傳手是公共的還是不是。

例如:該方法的公開二傳手

typeof(X).GetProperties(BindingFlags.SetProperty | 
         BindingFlags.Public | 
         BindingFlags.Instance) 
    .Where(prop => prop.GetSetMethod() != null) 
    .Select (x => x.Name).Dump(); 

GetSetMethod()回報,如果沒有一個返回null

由於屬性可能與setter具有不同的可見性,因此需要使用setter方法可見性進行過濾。

+1

上次我信任.CanWrite屬性!謝謝! – mcintyre321