【发布时间】:2018-05-07 01:46:49
【问题描述】:
鉴于下面的类和接口,我想知道为什么隐式转换:
ISomeModelAbstract<IBasicModel> x = new ConcreteClass();
不可能。我试过了
public interface ISomeModelAbstract<out T> where T: IBasicModel
但是我不能使用GetById 和GetAll 方法。我感谢任何帮助或提示。谢谢。
public interface IBasicModel {
string _id { get; set; }
}
public class SomeModel: IBasicModel {
public string _id { get; set; }
/* some other properties! */
}
public interface ISomeModelAbstract<T> where T: IBasicModel
{
bool Save(T model);
T GetById(string id);
IEnumerable<T> GetAll();
bool Update(string id, T model);
bool Delete(string id);
}
public abstract class SomeModelAbstract<T> : ISomeModelAbstract<T> where T : IBasicModel
{
public bool Save(T model)
{
throw new System.NotImplementedException();
}
public T GetById(string id)
{
throw new System.NotImplementedException();
}
public IEnumerable<T> GetAll()
{
throw new System.NotImplementedException();
}
public bool Update(string id, T model)
{
throw new System.NotImplementedException();
}
public bool Delete(string id)
{
throw new System.NotImplementedException();
}
}
public interface IConcreteClass: ISomeModelAbstract<SomeModel> { }
public class ConcreteClass: SomeModelAbstract<SomeModel>, IConcreteClass { }
【问题讨论】:
-
那是因为
ISomeModelAbstract<T>不是关于T的变体。如果您将其设为ISomeModelAbstract<out T>,那么您可以使用返回T的方法,但不能使用将T作为输入参数的方法。它可以是 covariant 或 contravariant 但不能同时是两者(这是您正在尝试的)。 -
为此,接口必须是协变的,这意味着泛型类型只会出现,但您有方法将其作为参数输入。
-
仅仅因为
SomeModelis-aIBasicModel而SomeModelAbstract<T>is-aISomeModelAbstract<T>它不意味着SomeModelAbstract<SomeModel>is-a @987654336 @.
标签: c# types least-common-ancestor