我有一个接口IJob,所有的作业类都从它继承,我有一个通用的存储库类,它将处理所有类型的IJob。
我面临的问题是,即使Repository<Job1>
是一种Repository<IJob>
,我也不能将Job1
转换为IJob
。
代码
internal class Program
{
public interface IJob { }
public class Job1 : IJob { }
public class Job2 : IJob { }
public class Repository<TJob>
where TJob : IJob
{
public List<TJob> GetJobs()
{
return new List<TJob>();
}
}
private static void Main(string[] args)
{
IJob iJob = new Job1(); // Valid
Repository<IJob> repo = new Repository<Job1>(); // Not Valid
}
}
有人能告诉我为什么这在C#中是不可能的吗?在C#泛型中有没有其他规则类型转换?
发布于 2016-03-16 22:37:06
如果需要协方差,则必须为存储库引入一个通用接口,并将GetJobs
方法的返回类型更改为IEnumerable<TJob>
internal class Program
{
public interface IJob { }
public class Job1 : IJob { }
public class Job2 : IJob { }
public interface IRepository<out TJob> where TJob : IJob
{
IEnumerable<TJob> GetJobs();
}
public class Repository<TJob> : IRepository<TJob> where TJob : IJob
{
public IEnumerable<TJob> GetJobs()
{
return new List<TJob>();
}
}
private static void Main(string[] args)
{
IJob iJob = new Job1(); // Valid
IRepository<IJob> repo = new Repository<Job1>(); // Also valid
}
}
有关协差和逆差的详情,请参阅:https://msdn.microsoft.com/en-us/library/dd799517%28v=vs.110%29.aspx
发布于 2016-03-16 22:25:34
Repository<IJob> repo = new Repository<Job1>(); // Not Valid
是的,因为它不是Repository<IJob>
。对于Repository<IJob>
,下面这一行是有效的:
repo.GetJobs().Add(new Job2());
现在,对于Repository<Job1>
,这一行是无效的。它不会编译。
所以你得到的错误是正确的。A Repository<Job1>
is not a Repository<IJob>
.
发布于 2016-03-16 22:29:55
你只是想要
Repository<IJob> repo = new Repository<IJob>();
然后,您可以将任何IJob
添加到存储库。
repo.Add(new Job1());
repo.Add(new Job2());
https://stackoverflow.com/questions/36038325
复制相似问题