![](/img/trans.png)
[英]Using C# Reflection, how to get Object's properties and their values if that Object is a property of Object that is inside of the List
[英]get a list of single property values in c# - reflection
我在努力理解反射在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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.