亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

方法泛型不同的接口

方法泛型不同的接口

C#
富國滬深 2023-09-16 17:55:06
為什么我不能將泛型方法與這樣的接口一起使用?我的參數的接口public interface IBaseParam {    string Name { get; }}public interface IComplexParam : IBaseParam {    string P1 { get; }    string P2 { get; }}使用泛型接口的類public interface ILauncherCommand {    void launch<T>(T parameters) where T : IBaseParam;}public class BaseCommand : ILauncherCommand {    string Name { get; }    public void launch<T>(T parameters) where T : IBaseParam {    }}public class ComplexCommand : ILauncherCommand {    string Name { get; }    public void launch<T>(T parameters) where T : IComplexParam {    }}ComplexCommand.launch是編譯器顯示問題的地方(CS0425)。IComplexParam繼承自IBaseParam,因此契約必須有效。僅當聲明泛型類時我才能編譯,但我想使用泛型方法而不是完整的泛型類下面的代碼可以工作,但它是一個泛型類public interface ILauncherCommand<T> where T : IBaseParam {    void launch(T parameters);}public class BaseCommand : ILauncherCommand<IBaseParam> {    string Name { get; }    public void launch(IBaseParam parameters) {    }}public class ComplexCommand : ILauncherCommand<IComplexParam> {    string Name { get; }    public void launch(IComplexParam parameters) {    }}
查看完整描述

1 回答

?
RISEBY

TA貢獻1856條經驗 獲得超5個贊

泛型方法強制您使用不變類型,這意味著您必須準確提供您指定的內容。


您正在尋找的是啟用協方差類型以允許使用更多派生類型。這只能在類級別完成:


請注意,這<in T>是指定協方差的方式。


public interface ILauncherCommand<in T> where T : IBaseParam

{

? ? void launch(T parameters);

}


public class BaseCommand<T> : ILauncherCommand<T> where T : IBaseParam??

{

? ? string Name { get; }


? ? public void launch(T parameters)

? ? {

? ? }

}


public class ComplexCommand<T> : ILauncherCommand<T> where T : IComplexParam

{

? ? string Name { get; }


? ? public void launch(T parameters)

? ? {

? ? }

}

在這種特定情況下,請注意 是<in >可選的,因為協方差是自動的。


查看完整回答
反對 回復 2023-09-16
  • 1 回答
  • 0 關注
  • 117 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號