C#-重载没有参数的模板化方法

说我有一个接口WorksWithType<T>和类MyClass同时实现WorksWithType<TypeA>和WorksWithType<TypeB>。


如果我的界面看起来像


public interface WorksWithType<T> {

     void DoSomething(T foo);

     void DoSomethingElse();

}

在中轻松实现两种不同的DoSomething方法重载MyClass。


public class MyClass : WorksWithType<TypeA>, WorksWithType<TypeB> {

{

    public void DoSomething(TypeA fooA) { ... } 

    public void DoSomething(TypeB fooB) { ... } 

    ...

}

但是,似乎没有实现的重载的方法DoSomethingElse。在我看来,我好像应该可以将界面上的签名更改为


void DoSomethingElse<T>();

然后用


public void DoSomethingElse<TypeA>() { ... } 

public void DoSomethingElse<TypeB>() { ... }  

如果有的话,这里的正确方法是什么?


人到中年有点甜
浏览 145回答 2
2回答

白板的微信

假设您希望的两个实现DoSomethingElse不同,则需要使用显式接口实现来区分调用:public class TypeA {}public class TypeB {}public interface IWorksWithType<T>{&nbsp; &nbsp; &nbsp;void DoSomething(T foo);&nbsp; &nbsp; &nbsp;void DoSomethingElse();}public class MyClass : IWorksWithType<TypeA>, IWorksWithType<TypeB>{&nbsp; &nbsp; public void DoSomething(TypeA fooA) {}&nbsp; &nbsp; public void DoSomething(TypeB fooB) {}&nbsp;&nbsp; &nbsp; // Note the syntax here - this indicates which interface&nbsp; &nbsp; // method you're implementing&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; void IWorksWithType<TypeA>.DoSomethingElse() {}&nbsp; &nbsp; void IWorksWithType<TypeB>.DoSomethingElse() {}}您不必使双方都使用显式接口实现。例如:public class MyClass : IWorksWithType<TypeA>, IWorksWithType<TypeB>{&nbsp; &nbsp; public void DoSomething(TypeA fooA) {}&nbsp; &nbsp; public void DoSomething(TypeB fooB) {}&nbsp;&nbsp; &nbsp; // Explicit interface implementation&nbsp; &nbsp; void IWorksWithType<TypeA>.DoSomethingElse() {}&nbsp; &nbsp; // Implicit interface implementation&nbsp; &nbsp; public void DoSomethingElse() {}}如果您不需要实现不同,那么当然可以使用三种方法:public class MyClass : IWorksWithType<TypeA>, IWorksWithType<TypeB>{&nbsp; &nbsp; public void DoSomething(TypeA fooA) {}&nbsp; &nbsp; public void DoSomething(TypeB fooB) {}&nbsp; &nbsp; // Implementation of both IWorksWithType<TypeA>.DoSomethingElse()&nbsp; &nbsp; // and IWorksWithType<TypeB>.DoSomethingElse()&nbsp; &nbsp; public void DoSomethingElse() {}}假设您要在接口上使用type参数。您可以将其放在方法上,但这实际上代表了一个非常不同的接口-并且您不能说MyClass只能调用DoSomethingElsetypeTypeA和TypeB。
打开App,查看更多内容
随时随地看视频慕课网APP