为什么接口列表不能使用实现类型?

Vac*_*ano 7 c# generics interface

我尚未学习的接口/泛型必须有一些基础.我希望现在能够学习它.

这是场景:

我有这个界面和类:

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

public class RealValue: IInterface
{
    public string TestValue { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

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

public class RandomTest: IMethodInterface
{
   public IInterface GetRealValue()
   {
       RealValue realValue = new RealValue();
       return realValue;
   }
 }
Run Code Online (Sandbox Code Playgroud)

请注意,我正在返回一个实现该接口的对象.

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

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

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

有没有解决的办法?当您实现上述方法的返回值时,如果您正在实现这样的接口,您会怎么做:

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.
}
Run Code Online (Sandbox Code Playgroud)

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

Pie*_*kel 10

原因是它List<RealValue>是一种特定类型,它不会继承List<IInterface>,因此无法转换.

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

IEnumerable<IInterface> GetRealValues();
Run Code Online (Sandbox Code Playgroud)

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

out关键字意味着两件事情:

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

  2. 由于这种限制,.NET知道T可以将其包含在继承的所有内容中T.由于这种限制,这保证是安全的操作.