代码之家  ›  专栏  ›  技术社区  ›  Lord Darth Vader

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

  •  1
  • Lord Darth Vader  · 技术社区  · 6 年前

    我试图测试一个私有的以下私有方法

    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。

    当使用复杂类型作为数组参数时,似乎找不到该方法

    1 回复  |  直到 6 年前
        1
  •  2
  •   TheGeneral    6 年前

    如果我正确理解这一点,这与clr如何计算参数数组有关。这是相当深入的,我已经看到埃里克·利珀特谈过好几次了。

    带有params数组的方法可以“normal”或“expanded”形式调用。正常形式就好像没有“参数”。展开的表单接受这些参数并将它们打包成一个自动生成的数组。如果这两种形式都适用,那么普通形式胜过扩展形式。

    它的长和短分别是:将params对象[]与数组混合 争论会导致混乱。尽量避免。如果你在 向params对象[]方法传递数组的情况, 以它的正常形式来称呼它。生成新对象[]…}然后把 数组中的参数。

    所以要解决这个问题

    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 })?