获取c#-反射中单个属性值的列表

获取c#-反射中单个属性值的列表,c#,generics,reflection,C#,Generics,Reflection,我正在努力理解C#中的反射是如何工作的。我设置了一个类名属性。当我使用下面的方法进行验证时,我需要获取ProductName值的列表。如何做到这一点 public class Product { public string ProductName { get; set; } } public class ClassName { public List<Product> Products { g

我正在努力理解C#中的反射是如何工作的。我设置了一个类名属性。当我使用下面的方法进行验证时,我需要获取ProductName值的列表。如何做到这一点

public class Product
{
    public string ProductName
    {
        get;
        set;
    }
}

public class ClassName
 {
    public List<Product> Products
    {
        get;
        set;
    }
 }
方法:

public bool Validate(object obj)
{
        PropertyInfo property = typeof(ClassName).GetProperty("Products");

        Value = (string)property.GetValue(obj, null); // how to get a list of values 
}

您必须将其强制转换为
列表

公共bool验证(对象obj){
如果(!(obj是ClassName))返回false;
PropertyInfo property=typeof(ClassName).GetProperty(“产品”);
Value=(List)property.GetValue(obj,null);
返回true;//或在此处实现您自己的验证
}

什么是
GenericTransaction
?您是否尝试将其强制转换为list?(list)property.GetValue(obj,null);虽然,它能破解你的问题。。。Alex是对的,你至少应该花时间阅读你自己的问题,并确保所有关键词都是正确的(即产品/产品以及产品/一般交易)我尝试过这个方法,但收到错误消息:对象与目标类型不匹配。什么是值数据类型?@user2857908您确定
obj
属于
ClassName
类型,这是您的错。@user2857908我更新了
Validate
方法的正确性,现在您应该看到没有任何异常,但是
Validate
返回
false
,因为传入的
obj
不是
ClassName
类型。
public bool Validate(object obj)
{
        PropertyInfo property = typeof(ClassName).GetProperty("Products");

        Value = (string)property.GetValue(obj, null); // how to get a list of values 
}
public bool Validate(object obj) {
  if(!(obj is ClassName)) return false;
  PropertyInfo property = typeof(ClassName).GetProperty("Products");  
  Value = (List<Product>)property.GetValue(obj, null);
  return true;//or your own validation implemented here
}