I am struggling to understand how a reflection works in C#. I set a property of class name. When I use a method (below) to validate, i need to get a list of ProductName values. How to do this?
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" });
Method:
public bool Validate(object obj)
{
PropertyInfo property = typeof(ClassName).GetProperty("Products");
Value = (string)property.GetValue(obj, null); // how to get a list of values
}
You have to cast it to 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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.