為什么我不能將泛型方法與這樣的接口一起使用?我的參數的接口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 >可選的,因為協方差是自動的。
- 1 回答
- 0 關注
- 117 瀏覽
添加回答
舉報
0/150
提交
取消