第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

C#-重載沒(méi)有參數(shù)的模板化方法

C#-重載沒(méi)有參數(shù)的模板化方法

C#
人到中年有點(diǎn)甜 2021-04-11 13:19:19
說(shuō)我有一個(gè)接口WorksWithType<T>和類(lèi)MyClass同時(shí)實(shí)現(xiàn)WorksWithType<TypeA>和WorksWithType<TypeB>。如果我的界面看起來(lái)像public interface WorksWithType<T> {     void DoSomething(T foo);     void DoSomethingElse();}在中輕松實(shí)現(xiàn)兩種不同的DoSomething方法重載MyClass。public class MyClass : WorksWithType<TypeA>, WorksWithType<TypeB> {{    public void DoSomething(TypeA fooA) { ... }     public void DoSomething(TypeB fooB) { ... }     ...}但是,似乎沒(méi)有實(shí)現(xiàn)的重載的方法DoSomethingElse。在我看來(lái),我好像應(yīng)該可以將界面上的簽名更改為void DoSomethingElse<T>();然后用public void DoSomethingElse<TypeA>() { ... } public void DoSomethingElse<TypeB>() { ... }  如果有的話,這里的正確方法是什么?
查看完整描述

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。


查看完整回答
反對(duì) 回復(fù) 2021-04-17
  • 2 回答
  • 0 關(guān)注
  • 164 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)