return different generics that implement same interface

只愿长相守 提交于 2021-02-10 09:33:53

问题


Considering there is a method

static IEnumerable<IComparable> q()
{
   return new List<string>();
}

I am trying to achieve the same but on my own classes and as a result i receive casting error cs0266

I tried to cast this way return (Common<Message>)new A(); but it results 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
}

How can the method return different generics that implement same interface?


回答1:


IEnumerable is covariant which is why the first block of code works. To do the same thing you need to make your T type paramater covariant by adding the out modifier:

interface Common<out T> where T : Message
{
    T Source { get; }
    void Show();
}

Now you can write code like this:

Common<Message> x = new A();


来源:https://stackoverflow.com/questions/57490565/return-different-generics-that-implement-same-interface

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!