一定有一些关于接口(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> 接口(interface)指定 T 可以是类,也可以是基类,因此您可以将方法更改为:

IEnumerable<IInterface> GetRealValues();

在 .NET 4.0 上。请注意,这仅有效,因为 IEnumerable 在模板参数上指定了 out 关键字。
out 关键字意味着两件事:
  • 之前放置 out 关键字的类型只能用于超出类的类型。所以,public T MyMethod() 是允许的,但 public void MyMethod(T myParam) 是不允许的,因为这进入了类;
  • 由于此限制,.NET知道T可以应用于从T继承的所有内容。由于限制,这保证是安全的操作。
  • 关于c# - 为什么接口(interface)列表不能使用实现类型?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4062165/

    10-13 08:07
    查看更多