gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:43:06 26 4
gpt4 key购买 nike

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

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

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

///<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 结合使用,但它出错了(释义):

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

最佳答案

要使用反射获取/设置您需要一个实例。要循环遍历列表中的项目,试试这个:

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
}

关于c# - 使用反射从类列表的属性中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10710156/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com