问题
Given two interfaces:
interface I1 {
int Foo();
}
interface I2 {
void Foo();
}
And a class:
class Test : I1, I2 {
int I1.Foo() {
Console.WriteLine("I1.Foo");
return default(int);
}
public void Foo() {
Console.WriteLine("I2.Foo");
}
}
How can I extend the interface I2 with I1 by keeping the methods named Foo?
I tried the following code but it doesn't compile:
interface I1 {
int Foo();
}
interface I2 : I1 {
void I2.Foo();
}
class Test : I2 { /* same code */ }
回答1:
It is unclear in the example what explicitly declaring I2.Foo() in the interface itself would accomplish if it were permitted. The specification (s. 13.4.1) allows the struct or class implementing an interface to declare an explicit member implementation. (Interfaces cannot declare any implementation, explicit or otherwise).
Thus, suppose we have defined:
interface IFoo
{
void Bar();
}
interface IBaz : IFoo
{
new void Bar();
}
interface IQux : IBaz { }
class A : IQux // equivalent to class A : IQux, IBaz, IFoo (spec sec. 13.4.6)
{
void IFoo.Bar()
{
Console.WriteLine("IFoo.Bar");
}
void IBaz.Bar()
{
Console.WriteLine("IBaz.Bar");
}
public void Bar()
{
Console.WriteLine("A.Bar");
}
// Not allowed: void IQux.Bar() {...}
// Since "The fully-qualified name of the interface member
// must reference the interface in which the member
// was declared" (s. 13.4.1)
}
Then the following driver shows the effect of the explicit interface method implementation.
public static void Main()
{
A a = new A();
a.Bar(); // prints A.Bar
(a as IFoo).Bar(); // prints IFoo.Bar
(a as IBaz).Bar(); // prints IBaz.Bar
(a as IQux).Bar(); // prints IBaz.Bar
}
回答2:
not quite sure what you are wanting it to do, but you can do :-
public interface I1
{
int Foo();
}
public interface I2:I1
{
new void Foo();
}
回答3:
It works only if the two methods have a different signature, which means that they must have a different number of parameters or different types of parameters or both.
Why not name your two methods GetFoo and DoFoo?
This would work
public interface I1
{
int Foo();
}
public interface I2 : I1
{
void Foo(int i);
}
This would also work
public interface I1
{
int GetFoo();
}
public interface I2 : I1
{
void DoFoo();
}
You could also declare a property. Properties consist of two methods: A getter and a setter.
public interface I
{
int Foo { get; set; }
}
public class C : I
{
private int _foo;
public int Foo
{
get {
// getter
return _foo;
}
set {
// setter
_foo = value;
}
}
}
来源:https://stackoverflow.com/questions/8963542/how-to-extend-an-interface-by-keeping-the-method-names