繁体   English   中英

使用泛型时无法隐式转换类型

[英]Cannot implicitly convert type when using generics

我试图在基类上设置一个值,但出现错误:

无法将类型'PersonService'隐式转换为'IMyInterface<IEntity>' 存在显式转换(您是否缺少演员表?)

当我尝试创建我的PersonService()它确实实现了IMyInterface<Person> Person实现了IEntity所以我无法弄清为什么它不起作用。

public interface IEntity { }
public class Person : IEntity { }
public interface IMyInterface<T> where T : IEntity { }
public class PersonService : IMyInterface<Person> { }
public abstract class Model : IEntity
{
    public IMyInterface<IEntity> DataService { get; set; }
}
public class Test : Model
{
    public Person Person { get; set; }
    public Test() : base()
    {
        DataService = new PersonService();
    }
}

IMyInterface<Person>不一定与IMyInterface<IEntity>兼容。 如果IMyInterface包含.Add(T item)方法怎么办? 如果允许您通过IMyInterface<IEntity>调用不是Person ,则该集合将以无效元素结尾,从而违反类型安全性。

但是,如果IMyInterface包含此类方法,并且始终安全,该怎么办? 在那种情况下,您可以通过使用协变类型来告诉编译器:

public interface IMyInterface<out T> where T : IEntity { }

现在,您的示例将编译。

您需要使接口协变(如果可能):

public interface IMyInterface<out T> where T : IEntity { }

然后,您将可以执行以下操作:

DataService = new PersonService();

因为DataServiceIMyInterface<IEntity>而不是IMyInterface<IEntity> IMyInterface<Person>

关于协方差的其他答案是解决此问题的好方法-另一个是引入一些泛型。

如果您像这样更改Model以指定实体的类型

public abstract class Model<TEntity> : IEntity 
            where TEntity : IEntity
{
    public IMyInterface<TEntity> DataService { get; set; }
}

并像这样Test

public class Test : Model<Person>
{
    public Person Person { get; set; }
    public Test() : base()
    {
        DataService = new PersonService();
    }
}

所有工作均符合预期:

http://rextester.com/EVBT53292

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM