考虑到有一个方法
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
is 协变 https://learn.microsoft.com/en-us/dotnet/standard/generics/covariance-and-contravariance这就是第一段代码起作用的原因。要做同样的事情,你需要让你的T
类型参数协变通过添加out https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-generic-modifier修饰符:
interface Common<out T> where T : Message
{
T Source { get; }
void Show();
}
现在你可以编写这样的代码:
Common<Message> x = new A();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)