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

标签 c# reflection

在我的 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/

相关文章:

c# - 使用 AWS SDK 对 S3 上传进行带宽限制

c# - 如何使用 C# 按下并释放它?

c# - 仅输出序列化时设置的 XML 元素

java - getMetaData() 抛出内部 NullPointerException

c# - CanRead 和 CanWrite 对于 PropertyInfo 意味着什么?

c# - 将 DataGrid 的 ItemsSource 绑定(bind)到列表

c# - 如何从从另一个文件夹中加载的程序集中获取类型?

java - 反射(reflection)是我最好的选择吗?

多个类的 C# 泛型方法

c# - 无法在 Aspx 页面中从 Codebehind 运行 Javascript 代码