【发布时间】:2019-08-22 15:24:28
【问题描述】:
为什么我不能将泛型方法与这样的接口一起使用?
我的参数接口
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) {
}
}
【问题讨论】: