c# - 为什么接口(interface)列表不能使用实现类型?

标签 c# generics interface

一定有一些关于接口(interface)/泛型的基础知识我还没有学过。我希望现在就学会它。

场景如下:

我有这个接口(interface)和类:

public interface IInterface
{
    string TestValue { get; set; }
}

public class RealValue: IInterface
{
    public string TestValue { get; set; }
}

如果我创建这样的方法,它编译得很好:

public class RandomTest: IMethodInterface
{
   public IInterface GetRealValue()
   {
       RealValue realValue = new RealValue();
       return realValue;
   }
 }

请注意,我正在返回一个实现该接口(interface)的对象。

现在,如果我向 RandomTest 类添加一个返回列表的方法,那么它就不再起作用了:

 public List<IInterface> GetRealValues()
 {
    List<RealValue> realValues = new List<RealValue>();
    return realValues;  // ERROR Here <- says it can't convert to a List<IInterface>
 }

所以,我的猜测是泛型无法解决这个问题,但为什么呢?

有解决办法吗?当上面方法的返回值被锁定时,你会怎么做,因为你正在实现这样的接口(interface):

public interface IMethodInterface
{
    IInterface GetRealValue();
    List<IInterface> GetRealValues(); // Can't just convert the return types to a concrete 
                                      // class because I am implementing this.  This 
                                      // interface is in a separate project that does not 
                                      // have the concrete classes.
}

还有希望吗?你会怎么做?

最佳答案

原因是List<RealValue>是特定类型,不继承List<IInterface> , 所以不能转换。

但是,在 .NET 4.0 中,您很幸运。界面IEnumerable<out T>指定 T可以是类,也可以是基类,因此您可以将方法更改为:

IEnumerable<IInterface> GetRealValues();

在 .NET 4.0 上。请注意,这仅适用于 IEnumerableout在模板参数上指定的关键字。

out关键字意味着两件事:

  1. out 之前的类型关键字只能用于类外的类型。所以,public T MyMethod()是允许的,但是 public void MyMethod(T myParam)不允许,因为这会进入类;

  2. 由于这个限制,.NET 知道 T可以适用于继承自 T 的所有内容.由于限制,这保证是安全操作。

关于c# - 为什么接口(interface)列表不能使用实现类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4062165/

相关文章:

java - 如果实例没有分配泛型类型,则每个循环问题中的泛型

php - 为这两个PHP类制作接口(interface)吗?

Java 编程,JFrame 问题

c# - C# 编译器是否删除了封装 debug.writeline 的 if

c# - 单元测试错误 "Object reference not set to an instance of an object."

c# - Autofac:在泛型方法中解析泛型接口(interface)

java - 接口(interface)和合约 : in this example

c# - 优化我的方法

c# - 解码 H264 帧 C#

java - 为什么类型转换在 Java 中不起作用