简体   繁体   English

获取C#中的单个属性值的列表-反射

[英]get a list of single property values in c# - reflection

I am struggling to understand how a reflection works in C#. 我在努力理解反射在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. 当我使用下面的方法进行验证时,我需要获取ProductName值的列表。 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> : 您必须将其强制转换为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