2 回答

TA貢獻(xiàn)1883條經(jīng)驗(yàn) 獲得超3個(gè)贊
假設(shè)您希望的兩個(gè)實(shí)現(xiàn)DoSomethingElse不同,則需要使用顯式接口實(shí)現(xiàn)來(lái)區(qū)分調(diào)用:
public class TypeA {}
public class TypeB {}
public interface IWorksWithType<T>
{
void DoSomething(T foo);
void DoSomethingElse();
}
public class MyClass : IWorksWithType<TypeA>, IWorksWithType<TypeB>
{
public void DoSomething(TypeA fooA) {}
public void DoSomething(TypeB fooB) {}
// Note the syntax here - this indicates which interface
// method you're implementing
void IWorksWithType<TypeA>.DoSomethingElse() {}
void IWorksWithType<TypeB>.DoSomethingElse() {}
}
您不必使雙方都使用顯式接口實(shí)現(xiàn)。例如:
public class MyClass : IWorksWithType<TypeA>, IWorksWithType<TypeB>
{
public void DoSomething(TypeA fooA) {}
public void DoSomething(TypeB fooB) {}
// Explicit interface implementation
void IWorksWithType<TypeA>.DoSomethingElse() {}
// Implicit interface implementation
public void DoSomethingElse() {}
}
如果您不需要實(shí)現(xiàn)不同,那么當(dāng)然可以使用三種方法:
public class MyClass : IWorksWithType<TypeA>, IWorksWithType<TypeB>
{
public void DoSomething(TypeA fooA) {}
public void DoSomething(TypeB fooB) {}
// Implementation of both IWorksWithType<TypeA>.DoSomethingElse()
// and IWorksWithType<TypeB>.DoSomethingElse()
public void DoSomethingElse() {}
}
假設(shè)您要在接口上使用type參數(shù)。您可以將其放在方法上,但這實(shí)際上代表了一個(gè)非常不同的接口-并且您不能說(shuō)MyClass只能調(diào)用DoSomethingElsetypeTypeA和TypeB。
- 2 回答
- 0 關(guān)注
- 164 瀏覽
添加回答
舉報(bào)