我收到以下这行service.job = new Job1<RealThing>();
的错误
无法隐式转换类型'Program.Job1<Program.Thing1>'到'程序.IJob<程序。IThing>'。存在显式转换(您是缺少演员阵容?(
我正在努力让它发挥作用,并理解为什么我在这里出现这个错误,但service.List = new List
();
的错误不同
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
Service service = new Service();
IJob<RealThing> job = new Job1<RealThing>();
RealThing rt = new RealThing();
service.job = new Job1<RealThing>();
service.List = new List<RealThing>();
service.GetSomething(rt);
//Console.WriteLine(service.GetSomething(rt));
}
public interface IThing { }
public class RealThing : IThing { }
public interface IJob<in T> where T : IThing
{
string GetSomething(T aThing);
}
public class Job1<T> : IJob<RealThing>
{
public string GetSomething(RealThing athing)
{
return "Job1.RealThing";
}
}
public class Service
{
public IJob<IThing> job { get; set; }
public IEnumerable<IThing> List { get; set; }
public string GetSomething(IThing aThing)
{
return job.GetSomething(aThing);
}
}
}
Job1类中的问题:
public class Job1<T> : IJob<RealThing>
Job1类(T(中的类型参数没有传递给IJob,所以这意味着T没有应用于IThing。
将你的课程重新调整为
public class Job1<T> : IJob<T>
或
public class Job1 : IJob<RealThing>
创建IJob<T1>
的实例和IJob<T2>
的另一个实例时,它们的类型不相同。因此,不能将IJob<RealThing>
分配给IJob<IThing>
您可以按如下方式重新制作它。但似乎通用的论点只是让事情变得复杂。
namespace ConsoleApp28
{
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var service = new Service<IJob<RealThing>, RealThing>();
var job = new Job1();
var rt = new RealThing();
service.job = new Job1();
service.List = new List<RealThing>();
service.GetSomething(rt);
//Console.WriteLine(service.GetSomething(rt));
}
public interface IThing
{
}
public class RealThing : IThing
{
}
public interface IJob<in T> where T : IThing
{
string GetSomething(T aThing);
}
public class Job1 : IJob<RealThing>
{
public string GetSomething(RealThing athing)
{
return "Job1.RealThing";
}
}
public class Service<TJob, T>
where TJob : IJob<T>
where T : IThing
{
public TJob job { get; set; }
public IEnumerable<IThing> List { get; set; }
public string GetSomething(T aThing)
{
return job.GetSomething(aThing);
}
}
}
}
一个IJob不能简单地消耗一个IThing吗?T一定是一个IThing吗?