簡體   English   中英

獲取C#中的單個屬性值的列表-反射

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM