如果属性名称定义为" name"如何使用Reflection获取属性值

时间:2016-01-25 10:32:47

标签: c# system.reflection

我有以下代码来比较两个集合......

    //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;
    }
}

代码似乎工作正常,除非我尝试对名为" name"的属性进行排序。在比较该属性时,变量propertie1propertie2都为空,并且代码因此而抛出异常。

所以我的问题是如何使用反射来获取名称为" name"?

的属性的值

2 个答案:

答案 0 :(得分:0)

顺便说一下, _property 变量设置?

这种扩展方法怎么样:

com.my.app.package.name

答案 1 :(得分:0)

好的,我想通了......我猜想做反射时大写的数字......

我需要将代码调用更改为...

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

由于该物业实际上被称为"名称"而不是"名称"