且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么C#4可选参数的接口定义没有强制执行的实现类?

更新时间:2023-11-13 23:16:04

更​​新:This问题是我的博客5月12日的2011年主题为感谢伟大的问题!

假设你有一个接口为你描述,以及实现其百类。然后你决定做接口的方法任选其一的参数之一。你是在暗示,正确的做法是让编译器迫使开发商找到每一个实现该接口的方法,并进行了参数可选呢?

Suppose you have an interface as you describe, and a hundred classes that implement it. Then you decide to make one of the parameters of one of the interface's methods optional. Are you suggesting that the right thing to do is for the compiler to force the developer to find every implementation of that interface method, and make the parameter optional as well?

假设我们这样做。现在假设开发商并没有源$ C ​​$ C为执行:

Suppose we did that. Now suppose the developer did not have the source code for the implementation:

// in metadata:
public class B 
{ 
    public void TestMethod(bool b) {}
}


// in source code
interface MyInterface 
{ 
    void TestMethod(bool b = false); 
}
class D : B, MyInterface {}
// Legal because D's base class has a public method 
// that implements the interface method

如何为D的作者应该使这项工作?他们是否需要在你的世界,调出B的作者的电话,请他们来取悦它们运B中使得该方法有一个可选参数的新版本?

How is the author of D supposed to make this work? Are they required in your world to call up the author of B on the phone and ask them to please ship them a new version of B that makes the method have an optional parameter?

这不会飞。如果的两个的人叫了B的作者,其中一人想默认是真实的,其中一个希望它是假的?如果有什么B的作者只是拒绝一起玩?

That's not going to fly. What if two people call up the author of B, and one of them wants the default to be true and one of them wants it to be false? What if the author of B simply refuses to play along?

也许在这种情况下,他们将需要说:

Perhaps in that case they would be required to say:

class D : B, MyInterface 
{
    public new void TestMethod(bool b = false)
    {
        base.TestMethod(b);
    }
}

建议的功能似乎在重新presentative力量没有相应的增加增添了不少不便的程序员。这是什么功能的吸引人的好处,这是合理成本的增加给用户?

The proposed feature seems to add a lot of inconvenience for the programmer with no corresponding increase in representative power. What's the compelling benefit of this feature which justifies the increased cost to the user?