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

时间:2013-11-26 10:35:19

标签: c# generics reflection

我很难理解反射在C#中是如何工作的。我设置了类名的属性。当我使用方法(如下)进行验证时,我需要获取ProductName值列表。这该怎么做?

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

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

App:

product.Add(new Product { ProductName = "whatever name 1" });
product.Add(new Product { ProductName = "whatever name 2" });

方法:

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

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

1 个答案:

答案 0 :(得分:1)

您必须将其投射到List<Product>

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
}