我有下面的代碼,以兩個集合彼此比較...如何使用反射得到,如果屬性的名稱定義爲「名」
//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;
}
}
代碼似乎工作正常,除非我嘗試排序名爲「名稱」的屬性。當比較該屬性時,變量propertie1
和propertie2
都爲空,並且代碼因此引發異常。
所以我的問題是如何使用反射來獲得名稱爲「名稱」的屬性的值?
什麼是例外Messag e? – tchelidze
異常是空引用消息...我會相應地更新我的代碼... –
顯示您正在比較的類型的POCO定義,反射代碼沒有錯? –