c# - 显式实现带有可选参数的接口(interface)的警告

标签 c# c#-4.0 compiler-warnings optional-parameters

我正在尝试使用可选参数来了解它们如何与接口(interface)一起工作,但我遇到了一个奇怪的警告。我的设置是以下代码:

 public interface ITestInterface
 {
     void TestOptional(int a = 5, int b = 10, object c = null);
 }

 public class TestClass : ITestInterface
 {

     void ITestInterface.TestOptional(int a = 5, int b = 5, object c = null)
     {
        Console.Write("a=" + a + " b=" + b + " c=" + c);
     }
 }

编译器给我以下警告:

  • 为参数“a”指定的默认值将无效,因为它适用于在不允许可选参数的上下文中使用的成员
  • 为参数“b”指定的默认值将无效,因为它适用于在不允许可选参数的上下文中使用的成员
  • 为参数“c”指定的默认值将无效,因为它适用于在不允许可选参数的上下文中使用的成员

如果我使用以下代码运行它:

class Program
{
    static void Main(string[] args)
    {
        ITestInterface test = new TestClass();
        test.TestOptional();
        Console.ReadLine();
    }
}

如我所料,我得到了“a=5 b=10 c=”的输出。

我的问题是什么是警告?它指的是什么上下文?

最佳答案

C# 中可选参数的问题是被调用者将对象视为 TestClass 还是 ITestInterface。在第一种情况下,类中声明的值适用。在第二种情况下,接口(interface)中声明的值适用。这是因为编译器使用静态可用的类型信息来构造调用。在显式接口(interface)实现的情况下,该方法永远不会“为类”调用,总是“为接口(interface)”调用

10.6.1 中的 C# 语言规范指出:

If optional parameters occur in an implementing partial method declaration (§10.2.7) , an explicit interface member implementation (§13.4.1) or in a single-parameter indexer declaration (§10.9) the compiler should give a warning, since these members can never be invoked in a way that permits arguments to be omitted.

关于c# - 显式实现带有可选参数的接口(interface)的警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5683111/

相关文章:

javascript - 如何在页面加载和自动点击时获取警报消息内容

c# - 部分/部分中的 asp.net mvs 部分?

c# - 使用 OrderBy<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>)

.net - Entity Framework nvarchar外键区分大小写

java - JList 移动列表程序

c# - 为什么这个程序只产生三个警告?

java - 使用泛型返回列表的接口(interface)会导致警告

c# - 如何使用 SignalR 在聊天应用程序中发送登录用户

c# - 安装有效但无法运行该应用程序

c# - 确保语句未优化 "away"