C# 使用反射从类列表中的属性中获取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10710156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:56:17  来源:igfitidea点击:

Using reflection to get values from properties from a list of a class

c#genericsreflectioncollections

提问by Dustin Kingen

I am trying to get the values from objects inside a list which is part of a main object.

我试图从列表中的对象中获取值,该列表是主对象的一部分。

I have the main object which contains various properties which can be collections.

我有一个包含各种属性的主要对象,这些属性可以是集合。

Right now I am trying to figure out how to access a generic list which is contained in the object.

现在我想弄清楚如何访问包含在对象中的通用列表。

///<summary>
///Code for the inner class
///</summary>
public class TheClass
{
    public TheClass();

    string TheValue { get; set; }
} //Note this class is used for serialization so it won't compile as-is

///<summary>
///Code for the main class
///</summary>
public class MainClass
{
    public MainClass();

    public List<TheClass> TheList { get; set; }
    public string SomeOtherProperty { get; set; }
    public Class SomeOtherClass { get; set }
}


public List<MainClass> CompareTheValue(List<object> MyObjects, string ValueToCompare)
{ 
    //I have the object deserialised as a list
    var ObjectsToReturn = new List<MainClass>();
    foreach(var mObject in MyObjects)
    {

        //Gets the properties
        PropertyInfo piTheList = mObject.GetType().GetProperty("TheList");

        object oTheList = piTheList.GetValue(MyObject, null);


        //Now that I have the list object I extract the inner class 
        //and get the value of the property I want
        PropertyInfo piTheValue = oTheList.PropertyType
                                          .GetGenericArguments()[0]
                                          .GetProperty("TheValue");

        //get the TheValue out of the TheList and compare it for equality with
        //ValueToCompare
        //if it matches then add to a list to be returned

        //Eventually I will write a Linq query to go through the list to do the comparison.
        ObjectsToReturn.Add(objectsToReturn);

    }
return ObjectsToReturn;
}

I've tried to use a SetValue()with MyObject on this, but it errors out with (paraphrased):

我试过SetValue()在这个上使用with MyObject ,但它出错了(释义):

object is not of type

对象不是类型

private bool isCollection(PropertyInfo p)
{
    try
    {
        var t = p.PropertyType.GetGenericTypeDefinition();
        return typeof(Collection<>).IsAssignableFrom(t) ||
               typeof(Collection).IsAssignableFrom(t);
    }
    catch
    {
        return false;
    }
    }
}

采纳答案by D Stanley

To Get/Set using reflection you need an instance. To loop through the items in the list try this:

要使用反射获取/设置,您需要一个实例。要遍历列表中的项目,请尝试以下操作:

PropertyInfo piTheList = MyObject.GetType().GetProperty("TheList"); //Gets the properties

IList oTheList = piTheList.GetValue(MyObject, null) as IList;

//Now that I have the list object I extract the inner class and get the value of the property I want

PropertyInfo piTheValue = piTheList.PropertyType.GetGenericArguments()[0].GetProperty("TheValue");

foreach (var listItem in oTheList)
{
    object theValue = piTheValue.GetValue(listItem, null);
    piTheValue.SetValue(listItem,"new",null);  // <-- set to an appropriate value
}

回答by CodeLikeBeaker

See if something like this helps you in the right direction: I got the same error a while back and this code snipped solved my issue.

看看这样的事情是否可以帮助您朝着正确的方向前进:不久前我遇到了同样的错误,这段代码被剪掉了解决了我的问题。

PropertyInfo[] properties = MyClass.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
  if (property.Name == "MyProperty")
  {
   object value = results.GetType().GetProperty(property.Name).GetValue(MyClass, null);
   if (value != null)
   {
     //assign the value
   }
  }
}