相关疑难解决方法(0)

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

我注意到,如果在接口上将参数指定为可选参数,则使用C#4中的可选参数,您不必在任何实现类上使该参数可选:

public interface MyInterface
{
    void TestMethod(bool flag = false);
}

public class MyClass : MyInterface
{
    public void TestMethod(bool flag)
    {
        Console.WriteLine(flag);
    }
}
Run Code Online (Sandbox Code Playgroud)

因此:

var obj = new MyClass();        
obj.TestMethod(); // compiler error

var obj2 = new MyClass() as MyInterface;
obj2.TestMethod(); // prints false
Run Code Online (Sandbox Code Playgroud)

有谁知道为什么可选参数设计为这样工作?

一方面,我认为覆盖接口上指定的任何默认值的能力是有用的,但老实说,我不确定您是否应该能够在接口上指定默认值,因为这应该是一个实现决策.

另一方面,这种断开意味着您不能总是交替使用具体类和接口.当然,如果在实现上指定了默认值,那么这不是问题,但是如果你将具体类作为接口公开(使用一些IOC框架来注入具体的类),那么真的没有具有默认值的点,因为调用者无论如何都必须始终提供它.

.net c# interface optional-parameters c#-4.0

347
推荐指数
4
解决办法
9万
查看次数

有没有理由在接口中声明可选参数?

您可以在接口方法中声明可选参数,但不需要实现类来将参数声明为可选参数,正如Eric Lippert解释的那样.相反,您可以在实现类中将参数声明为可选参数,但不能在接口中声明.

那么有什么理由在接口中声明可选参数吗?如果没有,为什么允许?

例子:

public interface IService1
{
    void MyMethod(string text, bool flag = false);
}

public class MyService1a : IService1
{
    public void MyMethod(string text, bool flag) {}
}

public class MyService1b : IService1
{
    public void MyMethod(string text, bool flag = true) { }
}

public interface IService2
{
    void MyMethod(string text, bool flag);
}

public class MyService2b : IService2
{
    public void MyMethod(string text, bool flag = false) { }
}
Run Code Online (Sandbox Code Playgroud)

c# optional-parameters c#-4.0

21
推荐指数
2
解决办法
2万
查看次数

避免重复接口的默认值

有时候,我有默认参数的接口,我想从调用实现方法实现类(除了从外面它).我也想使用它的默认参数.

但是,如果我只是按名称调用方法,则不能使用默认参数,因为它们仅在接口中定义.我可以在实现方法中重复默认规范,但这是不可取的,因为DRY和所有这些都需要(特别是编译器不会检查它们实际上是否与接口的默认值匹配!)

我通过引入所谓的构件解决这个_this因为这是相同的this,除了它被声明为接口类型.然后当我想使用默认参数时,我用方法调用_this.这是示例代码:

public interface IMovable
{
    // I define the default parameters in only one place
    void Move(int direction = 90, int speed = 100);
}

public class Ball: IMovable
{
    // Here is my pattern
    private readonly IMovable _this;

    public Ball()
    {
        // Here is my pattern
        _this = this;
    }

    // I don't want to repeat the defaults from the interface here, e.g.
    // public void Move(int direction = …
Run Code Online (Sandbox Code Playgroud)

c#

11
推荐指数
2
解决办法
202
查看次数

标签 统计

c# ×3

c#-4.0 ×2

optional-parameters ×2

.net ×1

interface ×1