【问题标题】:Optional parameters in explicitly implemented interfaces显式实现的接口中的可选参数
【发布时间】:2012-10-04 15:16:22
【问题描述】:
public interface IFoo
{
    void Foo(bool flag = true);
}

public class Test : IFoo
{
    void IFoo.Foo(bool flag = true) //here compiler generates a warning
    {

    }
}

警告说给定的默认值将被忽略,因为它在不允许的上下文中使用。

为什么显式实现的接口不允许使用可选参数?

【问题讨论】:

  • 为什么需要覆盖 IFoo 中指定的默认参数?

标签: c# optional-parameters explicit-interface


【解决方案1】:

显式实现的接口方法总是调用,其编译时类型是接口,而不是特定的实现。编译器查看它“知道”它正在调用的方法声明的可选参数。当它只知道目标表达式为IFoo 类型时,您如何期望它知道从Test.Foo 获取参数?

IFoo x = new Test();
x.Foo(); // How would the compiler know to look at the Test.Foo declaration here?

【讨论】:

  • 我不认为它试图覆盖它。我认为必须逐字逐句地声明实现类似于接口声明......我什至不是要覆盖它。现在我明白了,这个假设是绝对错误的......现在这个警告确实有道理。
  • 您并没有真正“覆盖”——您是在实施
  • 这就是为什么我想,编译器不会想,我想改变参数的默认值
【解决方案2】:

我会使用方法重载。

public interface IFoo
{
    void Foo(bool flag);
    void Foo();
}

public class Test : IFoo
{
    void Foo() {
        this.Foo(true);
    }

    void Foo(bool flag) {
         // Your stuff here.
    }
}

【讨论】:

  • 糟糕... :D 我会改变我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-23
  • 1970-01-01
  • 1970-01-01
  • 2011-02-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多