gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:02:01 26 4
gpt4 key购买 nike

一定有一些关于接口(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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com