2 回答
TA贡献1883条经验 获得超3个赞
假设您希望的两个实现DoSomethingElse不同,则需要使用显式接口实现来区分调用:
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() {}
}
您不必使双方都使用显式接口实现。例如:
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() {}
}
如果您不需要实现不同,那么当然可以使用三种方法:
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() {}
}
假设您要在接口上使用type参数。您可以将其放在方法上,但这实际上代表了一个非常不同的接口-并且您不能说MyClass只能调用DoSomethingElsetypeTypeA和TypeB。
- 2 回答
- 0 关注
- 144 浏览
添加回答
举报