【发布时间】:2011-05-16 12:19:11
【问题描述】:
可能重复:
C# 4: conflicting overloaded methods with optional parameters
我只是进行了一项小型研究并创建了下一个代码。
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 个参数的短方法。当然,所有这些都以相同的方式工作并且没有接口。
谢谢
【问题讨论】:
-
因此,如果它在有和没有界面的情况下都以相同的方式工作,为什么要在您的问题中显示界面?这个想法是使用重现行为所需的最少数量的代码。这让我们专注于实际问题,而不是无关紧要的细节。
-
另外,这肯定是不是运算符重载,而是方法重载,完全不同。
-
主要问题是可选参数,而不是接口。
-
如果您对这些主题感兴趣,您可能想在本周查看我的博客。我正在运行一系列关于接口和可选参数声明如何在 C# 中工作的系列文章。
标签: c# .net interface overloading overload-resolution