为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
人到中年有点甜 2021-04-11 13:19:19
说我有一个接口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>() { ... }  如果有的话,这里的正确方法是什么?
查看完整描述

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。


查看完整回答
反对 回复 2021-04-17
  • 2 回答
  • 0 关注
  • 144 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信