加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:07:15 所属栏目:百科 来源:网络整理
导读:我尚未学习的接口/泛型必须有一些基础.我希望现在能够学习它. 这是场景: 我有这个界面和类: public interface IInterface{ string TestValue { get; set; }}public class RealValue: IInterface{ public string TestValue { get; set; }} 如果我创建这样的
我尚未学习的接口/泛型必须有一些基础.我希望现在能够学习它.

这是场景:

我有这个界面和类:

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继承的所有东西.由于这个限制,这可以保证是一个安全的操作.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读