24

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

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

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

///<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()在此上使用 with MyObject ,但它出错(解释):

对象不是类型

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

2 回答 2

31

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

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
}
于 2012-05-22T21:23:17.703 回答
6

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

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
   }
  }
}
于 2012-05-22T21:15:57.490 回答