[英]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();
因為DataService
是IMyInterface<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();
}
}
所有工作均符合預期:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.