2016-01-25 57 views
-1

我有下面的代碼,以兩個集合彼此比較...如何使用反射得到,如果屬性的名稱定義爲「名」

//code invocation 
    CollectionComparer comp = new CollectionComparer("name", "ASC"); 
    this.InnerList.Sort(comp); 

類的屬性值

public class CollectionComparer : IComparer 
{ 
    private String _property; 
    private String _order; 

    public CollectionComparer(String Property, String Order) 
    { 
     this._property = Property; 
     this._order = Order; 
    } 

    public int Compare(object obj1, object obj2) 
    { 
     int returnValue; 

     Type type = obj1.GetType(); 
     PropertyInfo propertie1 = type.GetProperty(_property); // returns null here 
     Type type2 = obj2.GetType(); 
     PropertyInfo propertie2 = type2.GetProperty(_property); // returns null here 

     object finalObj1 = propertie1.GetValue(obj1, null); // Null Reference Exception thrown here, because propertie1 is null 
     object finalObj2 = propertie2.GetValue(obj2, null); 

     IComparable Ic1 = finalObj1 as IComparable; 
     IComparable Ic2 = finalObj2 as IComparable; 

     if (_order == "ASC") 
     { 
      returnValue = Ic1.CompareTo(Ic2); 
     } 
     else 
     { 
      returnValue = Ic2.CompareTo(Ic1); 
     } 

     return returnValue; 
    } 
} 

代碼似乎工作正常,除非我嘗試排序名爲「名稱」的屬性。當比較該屬性時,變量propertie1propertie2都爲空,並且代碼因此引發異常。

所以我的問題是如何使用反射來獲得名稱爲「名稱」的屬性的值?

+0

什麼是例外Messag e? – tchelidze

+0

異常是空引用消息...我會相應地更新我的代碼... –

+2

顯示您正在比較的類型的POCO定義,反射代碼沒有錯? –

回答

0

好吧,我想通了......我猜大寫計數做反射的時候......

我需要改變代碼的調用來.. 。

//code invocation 
CollectionComparer comp = new CollectionComparer("Name", "ASC"); 
this.InnerList.Sort(comp); 

由於物業竟是所謂的「名」,而不是「名」

0

順便說一句,是_property變量集?

這個怎麼樣擴展方法:

public static object GetProperty(this object instance, string name) 
    { 
     if (instance == null) 
      throw new ArgumentNullException("instance"); 

     if (name == null) 
      throw new ArgumentNullException("name"); 

     Type type = instance.GetType(); 
     PropertyInfo property = type.GetProperty(name, BindingFlags.Public | BindingFlags.Instance); 

     if (property == null) 
      throw new InvalidOperationException(string.Format("Type {0} does not have a property {1}", type, name)); 

     object result = property.GetValue(instance, null); 

     return result; 
    } 
+0

我已經試過將bindingflags改爲這個'type.GetProperty(名字,BindingFlags.Public | BindingFlags.Instance);'我仍然得到一個空引用 –

+0

你傳入了什麼對象到比較方法?他們是否有「名字」財產? –

相關問題