复杂类型的私有对象调用数组

Private Object Invoke Array of complex type

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

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。

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

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

可以以 "normal" 或 "expanded" 形式调用带有参数数组的方法。正常形式就好像没有 "params"。扩展形式获取参数并将它们捆绑到一个自动生成的数组中。如果两种形式都适用,则普通形式胜过扩展形式。

The long and the short of it is: mixing params object[] with array arguments is a recipe for confusion. Try to avoid it. If you are in a situation where you are passing arrays to a params object[] method, call it in its normal form. Make a new object[] { ... } and put the arguments into the array yourself.

所以要解决这个问题

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

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

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

Why does params behave like this?

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