2017-09-06 170 views
2

在我的C#项目中,我对第三方库有依赖性。现在我想为我的项目编写一份自动验收测试。但是为了调用测试,我需要来自第三方库的一个类的实例。使用反射,我设法设置的价值,因为我需要他们除了一个。c#反射改变属性的方法

这里是我有问题的相关类:

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:找不到属性集方法。

从这些信息中我发现,这个班必须像我上面描述的那样。

现在我想继续这一些如何。有没有人有个想法,当我访问sysRes.Positions时,我的positions是由get方法返回的?或者有没有办法改变get方法?

+0

阅读本up.might帮助https://stackoverflow.com/questions/135020/advantages-to-using -private-static-methods –

回答

1

您可以使用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

希望帮助,

+0

你是英雄! ;) 这工作得很好。非常感谢! – Konstantin

0

{get;}只有属性可以有一个后台字段,但Positions可能会返回完全不同的东西(不是一个后台字段的值,但可能是一个函数的结果)。

您的代码可以接受ISystemResults,您可以模拟,在真实代码中您可以拥有一个类SystemResultsFacade,它可以在内部调用第三方代码。

+0

这是真的。没有考虑到这一点。 – Konstantin

+0

@PeterDuniho好点,谢谢。我在说废话 - 我在考虑基于表情的属性。答案已更新。 – mayu