4

重複の可能性:
C# 4: オーバーロードされたメソッドとオプションのパラメーターの競合

ちょっとした調査が 1 つだけあり、次のコードを作成しました。

namespace Test {
class Program
{
    public interface ITestA
    {
        void MethodA(int a, int b);
    }

    public class TestAClass : ITestA
    {
        public void MethodA(int a, int b)
        {
            Console.WriteLine("MethodA with param");
        }

        public void MethodA(int a, int b, bool logic = true)
        {
            Console.WriteLine("MethodA logic with param");
        }
    }

    public interface ITestB
    {
        void MethodA(int a, int b, bool logic = true);
    }

    public class TestBClass : ITestB
    {
        public void MethodA(int a, int b)
        {
            Console.WriteLine("MethodB with param");
        }         

        public void MethodA(int a, int b, bool logic = true)
        {
            Console.WriteLine("MethodB logic with param");
        }
    }

    static void Main(string[] args)
    {
        var testA = new TestAClass();
        testA.MethodA(1, 1);            
        var testB = new TestBClass();
        testB.MethodA(1, 1);   
    }
} }

コンパイラが常に 2 つのパラメーターを持つ短いメソッドを選択する理由について質問があります。そしてもちろん、これらはすべて同じ方法でインターフェイスなしで機能します。

ありがとう

4

2 に答える 2

3

This boils down to how the compiler treats named and optional parameters.
Check out this article at MSDN for more information, especially the paragraph Overload Resolution.

If two candidates are judged to be equally good, preference goes to a candidate that does not have optional parameters for which arguments were omitted in the call. This is a consequence of a general preference in overload resolution for candidates that have fewer parameters.

This is why in your case the compiler chooses the method without any optional parameters.

于 2011-05-16T12:34:32.843 に答える
1

コンパイラは、メソッドの呼び出しに完全に対応するメソッドを見つけてそれを使用するためです。
最初の方法が失敗した場合、コンパイラは他の適切なメソッドを検索します。

于 2011-05-16T12:24:45.070 に答える