C# 如果属性名称定义为“0”,如何使用反射获取属性值;名称“;
我有以下代码将两个集合相互比较C# 如果属性名称定义为“0”,如何使用反射获取属性值;名称“;,c#,system.reflection,C#,System.reflection,我有以下代码将两个集合相互比较 //code invocation CollectionComparer comp = new CollectionComparer("name", "ASC"); this.InnerList.Sort(comp); 阶级 代码似乎工作得很好,除非我尝试对名为“name”的属性进行排序。比较该属性时,变量propertie1和propertie2均为空,因此代码引发异常 所以我的问题是如何使用反射来获取一个名为“name”的属性的值?顺
//code invocation
CollectionComparer comp = new CollectionComparer("name", "ASC");
this.InnerList.Sort(comp);
阶级
代码似乎工作得很好,除非我尝试对名为“name”的属性进行排序。比较该属性时,变量propertie1
和propertie2
均为空,因此代码引发异常
所以我的问题是如何使用反射来获取一个名为“name”的属性的值?顺便问一下,\u属性是否设置了变量 这个扩展方法怎么样:
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;
}
好吧,我知道了。。。我猜在做反射时大写是很重要的 我需要将代码调用更改为
//code invocation
CollectionComparer comp = new CollectionComparer("Name", "ASC");
this.InnerList.Sort(comp);
由于该属性实际上被称为“Name”,而不是“Name”什么是异常消息?异常是空引用消息。。。我将相应地更新我的代码…显示您正在比较的类型的POCO定义,反射代码没有问题吗?哪里是
name
?显示它是如何定义的。或者干脆自己使用合适的方法,因为您正在处理BindingFlags
或者甚至可能试图获取字段
值?实际的类看起来如何obj1
是一个来自的实例?我已经尝试将BindingFlags更改为这个类型.GetProperty(名称,BindingFlags.Public | BindingFlags.instance);代码>,我仍然得到一个空引用,您将向Compare方法传递什么对象?他们有“名称”属性吗
//code invocation
CollectionComparer comp = new CollectionComparer("Name", "ASC");
this.InnerList.Sort(comp);