2013-03-15 57 views
4

我需要從MyClass獲取屬性列表,不包括「只讀」屬性,我可以得到它們嗎?如何從類中獲取「ReadOnly」或「WriteOnly」屬性?

public class MyClass 
{ 
    public string Name { get; set; } 
    public int Tracks { get; set; } 
    public int Count { get; } 
    public DateTime SomeDate { set; } 
} 

public class AnotherClass 
{ 
    public void Some() 
    { 
     MyClass c = new MyClass(); 

     PropertyInfo[] myProperties = c.GetType(). 
             GetProperties(BindingFlags.Public | 
                BindingFlags.SetProperty | 
                BindingFlags.Instance); 
     // what combination of flags should I use to get 'readonly' (or 'writeonly') 
     // properties? 
    } 
} 

而在去年,coluld我得到「時間排序?我知道添加排序依據<>,但如何?我只是使用擴展。 在此先感謝。

+0

有'PropertyInfo'上的幾個屬性指示讀/寫性 – 2013-03-15 18:13:59

+0

'myProperties.IsReadOnly'屬性PropertyInfo []屬性之一 – MethodMan 2013-03-15 18:15:57

回答

9

不能使用的BindingFlags指定或者只讀或只寫屬性,但你可以枚舉返回的屬性,然後測試的PropertyInfo的的CanRead和CanWrite屬性,像這樣:

PropertyInfo[] myProperties = c.GetType().GetProperties(BindingFlags.Public | 
                BindingFlags.SetProperty | 
                BindingFlags.Instance); 

foreach (PropertyInfo item in myProperties) 
{ 
    if (item.CanRead) 
     Console.Write("Can read"); 

    if (item.CanWrite) 
     Console.Write("Can write"); 
} 
+0

道歉,我忘記了排序請求 - 你想如何排序?通過讀\寫,只讀,只寫或名稱等? – 2013-03-15 18:20:48

+0

如果你可以展示所有你說的例子,我會很感激。 – Shin 2013-03-15 18:33:00

+3

我知道了,PropertyInfo [] ... .Where(p => p.CanWrite).OrderBy(x => x.Name).ToArray(); – Shin 2013-03-15 19:10:11