返回实现相同接口的不同泛型 [英] return different generics that implement same interface

查看:58
本文介绍了返回实现相同接口的不同泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑到一种方法

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

我正在尝试实现相同的目标,但是在我自己的班级上,结果收到转换错误cs0266

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

我试图以这种方式强制转换 return(Common< Message>)new A(); ,但结果为 InvalidCastException

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?

推荐答案

IEnumerable

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();

这篇关于返回实现相同接口的不同泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆