考虑到有一个方法
static IEnumerable<IComparable> q()
{
return new List<string>();
}
我正在尝试实现相同的目标,但在我自己的类上,结果我收到转换错误 cs0266
我试图以这种方式投return (Common<Message>)new A();
但结果InvalidCastException
interface Common<T> where T : Message
{
T Source { get; }
void Show();
}
interface Message
{
string Message { get; }
}
class AMsg : Message
{
public string Message => "A";
}
class A : Common<AMsg>
{
public AMsg Source => new AMsg();
public void Show() { Console.WriteLine(Source.Message); }
}
static Common<Message> test()
{
return new A(); //CS0266
}
该方法如何返回实现相同接口的不同泛型?
IEnumerable
是协变的,这就是第一个代码块工作的原因。要做同样的事情,你需要通过添加out
修饰符来使T
类型参数协变:
interface Common<out T> where T : Message
{
T Source { get; }
void Show();
}
现在你可以编写这样的代码:
Common<Message> x = new A();