微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

这是场景:

我有这个界面和类:

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;
   }
 }

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

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

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

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

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

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上.请注意,这仅适用,因为IEnumerable在模板参数上指定了out关键字.

out关键字意味着两件事:

>放置out关键字之前的类型只能用于类外的类型.因此,允许公共T MyMethod(),但不允许公共void MyMethod(T myParam),因为这进入了类;>由于这个限制,.NET知道T可以被装入从T继承的所有东西.由于这个限制,这可以保证是一个安全的操作.

原文地址:https://www.jb51.cc/csharp/100783.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐