Frage

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

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

    }
}

The warning says that the given default value will be ignored as it is used in the context which does not allow it.

Why are optional parameters not allowed for explicitly implemented interfaces?

War es hilfreich?

Lösung

Explicitly implemented interface methods are always called with a target whose compile-time type is the interface, not an specific implementation. The compiler looks at the optional parameters declare by the method it "knows" it's invoking. How would you expect it to know to take the parameters from Test.Foo when it only knows of the target expression as type IFoo?

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

Andere Tipps

I would use method overloading.

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.
    }
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top