我在努力理解反射在C#中的工作方式。我设置了一个类名的属性。当我使用下面的方法进行验证时,我需要获取ProductName值的列表。这该怎么做?
public class Product
{
public string ProductName
{
get;
set;
}
}
public class ClassName
{
public List<Product> Products
{
get;
set;
}
}
应用程序:
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
}
您必须将其转换为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
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句