【问题标题】:Using reflection to get values from properties from a list of a class使用反射从类列表中的属性中获取值
【发布时间】:2012-05-29 10:10:03
【问题描述】:

我正在尝试从作为主对象一部分的列表中的对象获取值。

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

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

///<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;
}

我尝试在此上使用 SetValue() 和 MyObject,但出现错误(释义):

对象不是类型

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

【问题讨论】:

  • 你试图反映的类的相关部分的代码可能有点有用。
  • 因为 List 继承了 IList 你可以通过更改为 IList oTheList 来解决这个问题吗?
  • 这还能编译吗? oTheList 是一个 object,它没有名为 PropertyType 的属性。
  • @TonyHopkinson 我添加了更多信息和相关代码。
  • 你为什么要使用反射来做到这一点?我觉得我错过了什么。

标签: c# generics reflection collections


【解决方案1】:

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

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
}

【讨论】:

  • 看来此方法可能适用于访问列表。我已经实现了一个函数来检查类型是否是一个集合。
  • 这应该很容易 -- bool isCollection = (oTheList is ICollection);
  • 很好,但缺少关于如何实现设置嵌套列表的说明。例如 MyObject.MyList[0].SecondList[1].SomeValue
  • 所以迭代内部项目 - 这并不难。或者,如果您遇到困难,请再问一个问题。您是否真的希望您评论的所有这些答案都能为每种可能的情况提供示例,或者只是无法弄清楚的情况?
【解决方案2】:

看看这样的事情是否能帮助你朝着正确的方向前进:前段时间我遇到了同样的错误,这段代码解决了我的问题。

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
   }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-14
    相关资源
    最近更新 更多