我很难理解反射在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
}
答案 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
}