使用默认参数的基本方法调用隐藏了其他方法

时间:2017-01-06 21:07:54

标签: c#-4.0

我理解使用参数调用基本方法将默认为没有任何默认参数的方法。大!完全可以理解!

Resolving Ambiguities with Optional Parameters and Named Arguments

但是,请考虑这种情况

using System;

class Class1 {
    public virtual string method1( string test ) {
        return test;
    }
}

class Class2 : Class1 {

    // Method is hidden!
    public override string method1( string test ) {
        return test;
    }

    public virtual string method1( string test, string test2 = " - this shouldn't be called" ) {
        return test + test2;
    }
}

class Class3 : Class2 {
    static int Main( string[] args ) {

        var c = new Class3();
        string theString;

        theString = c.test1();
        System.Console.WriteLine( theString ); // "Test - this shouldn't be called"

        theString = c.test2( );
        System.Console.WriteLine( theString ); // "Test"

        return 0;
    }

    public string test1() {
        return base.method1( "test" ); // calls base.method1( string, string )
    }

    public string test2() {
        return ( ( Func<string, string> )base.method1)("test"); // calls base.method1( string )
    }
}

显然,调用基本方法的预期行为应该只打印出“Test”,但它不会打印,而是使用默认参数调用该方法。我还是IL的新手,但它也表明它明确地解析了默认参数的方法。

这基本上隐藏了子类中的方法签名方法(字符串)。

这到底发生了什么?

这是C#中的错误吗?编译器中的错误?

在支持的生成链中,方法调用是否更高,具有优先权 在他们的孩子的覆盖电话?

我有什么遗失的吗?

对于好奇,通过使用委托函数

解决了问题
( ( Func<string, string> )base.method)("Test"); // prints out "Test"

**编辑 - 如果复制粘贴

,代码现在编译

0 个答案:

没有答案
相关问题