【问题标题】:Private Object Invoke Array of complex type复杂类型的私有对象调用数组
【发布时间】:2018-12-06 07:00:49
【问题描述】:

我正在尝试使用以下私有方法测试私有方法

public class Test
{        
        private bool PVTMethod1(Guid[] Parameter1)
        {
            return true;
        }

        private bool PVTMethod2(RandomClass[] Parameter2)
        {
            return true;
        }
 }

public class RandomClass
{
    public int Test { get; set; }
}

使用以下测试方法

    [TestClass]
    public TestClass1
    {
            [TestMethod]
            public void SomUnitTest()
            {
                Test _helper = new Test();

                PrivateObject obj = new PrivateObject(_helper);
                bool response1 = (bool)obj.Invoke("PVTMethod1", new Guid[0]);

                bool response2 = (bool)obj.Invoke("PVTMethod2", new RandomClass[0]);
            }
    }

第二次调用失败并出现 System.MissingMethodException。

使用复杂类型作为数组参数时好像找不到方法

【问题讨论】:

    标签: c# unit-testing privateobject.invoke


    【解决方案1】:

    如果我理解正确,这是与 clr 如何计算参数数组有关的怪癖。这非常深入,我已经看到 Eric Lippert 多次谈论它。

    可以以“正常”或“扩展”形式调用具有参数数组的方法。正常形式好像没有“参数”。扩展形式采用参数并将它们捆绑到自动生成的数组中。如果两种形式都适用,则普通形式胜过扩展形式。

    它的长短是:将参数对象[]与数组混合 争论是混乱的秘诀。尽量避免它。如果你在一个 将数组传递给 params object[] 方法的情况, 以正常形式调用它。制作一个新对象[] { ... } 并将 自己将参数放入数组中。

    所以要解决这个问题

    bool response2 = (bool)obj.Invoke("PVTMethod2", (object)new RandomClass[0]);
    

    bool response2 = (bool)obj.Invoke("PVTMethod2", new object {new RandomClass[0]});
    

    我不会假装知道 CLR 的内部,但是如果您有兴趣,可以查看这些问题

    Attribute with params object[] constructor gives inconsistent compiler errors

    C# params object[] strange behavior

    Why does params behave like this?

    Is there a way to distingish myFunc(1, 2, 3) from myFunc(new int[] { 1, 2, 3 })?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-02
      • 1970-01-01
      • 2011-01-26
      • 2018-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-04
      相关资源
      最近更新 更多