使用反射从类列表中的属性中获取值
本文关键字:属性 获取 列表 反射 | 更新日期: 2023-09-27 18:35:12
我正在尝试从作为主对象一部分的列表内的对象中获取值。
我有一个主要对象,其中包含各种可以成为集合的属性。
现在我正在尝试弄清楚如何访问对象中包含的通用列表。
///<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;
}
我试图在这个问题上使用 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;
}
}
}
要使用反射获取/设置,您需要一个实例。 要遍历列表中的项目,请尝试以下操作:
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
}
}
}