gpt4 book ai didi

c#反射改变属性的get方法

转载 作者:行者123 更新时间:2023-11-30 23:09:04 24 4
gpt4 key购买 nike

在我的 C# 项目中,我依赖于第 3 方库。现在我想为我的项目编写一个自动化验收测试。但是,要调用测试,我需要第 3 方库中的类实例。使用反射,我设法设置了我需要的值。

这是我遇到问题的相关类:

public class SystemResults
{
// There must be something like this. However I cannot see it as it is private.
private List<Positions> xyz = new List<Positions>();

public IList<Positions> Positions
{
get
{
return xyz;
}

// This property does not have a set method
}
}

到目前为止,这是我尝试过的:

private void InitSystemResults(Type trueSysResType, SystemResults sysRes)
{
List<Position> positions = ImporterTools.GetPositions(PositionsCsv);
trueSysResType.GetProperty("Positions").SetValue(sysRes, positions); // ==> Here I get an exception
}

当我调用 SetValue() 方法时,抛出了以下异常。

System.ArgumentException : Property set method not found.

根据这些信息,我发现该类必须像我上面描述的那样。

现在我想以某种方式继续进行。有没有人知道当我访问 sysRes.Positions 时如何实现,我的 positions 由 get 方法返回?或者有没有办法改变get方法?

最佳答案

您可以使用BindingFlags.NonPublic,

FieldInfo[] fields = typeof(SystemResults).GetFields(
BindingFlags.NonPublic |
BindingFlags.Instance).ToArray(); // gets xyz and the other private fields

List<int> testResults = new List<int>() { 1,23,4,5,6,7}; // list of integer to set

SystemResults sysres = new SystemResults(); // instance of object
fields[0].SetValue(sysres, testResults); // I know that fields[0] is xyz (you need to find it first),
// sets list of int to object

enter image description here

希望有所帮助,

关于c#反射改变属性的get方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46067221/

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