使用reflection从类列表中的属性中获取值

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

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

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

/// ///Code for the inner class /// public class TheClass { public TheClass(); string TheValue { get; set; } } //Note this class is used for serialization so it won't compile as-is /// ///Code for the main class /// public class MainClass { public MainClass(); public List TheList { get; set; } public string SomeOtherProperty { get; set; } public Class SomeOtherClass { get; set } } public List CompareTheValue(List MyObjects, string ValueToCompare) { //I have the object deserialised as a list var ObjectsToReturn = new List(); 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; } 

我试图在这上面使用带有MyObject的SetValue() ,但它出错(释义):

对象不是类型

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

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

 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 } 

看看这样的东西是否可以帮助你朝着正确的方向前进:我在一段时间内得到了同样的错误,这段代码剪断解决了我的问题。

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