我有一个泛型类,我想创建它的列表。然后在运行时,我得到项目的类型
public class Job<T>
{
public int ID { get; set; }
public Task<T> Task { get; set; }
public TimeSpan Interval { get; set; }
public bool Repeat { get; set; }
public DateTimeOffset NextExecutionTime { get; set; }
public Job<T> RunOnceAt(DateTimeOffset executionTime)
{
NextExecutionTime = executionTime;
Repeat = false;
return this;
}
}
List<Job<T>> x = new List<Job<T>>();
public void Example()
{
//Adding a job
x.Add(new Job<string>());
//The i want to retreive a job from the list and get it's type at run time
}
如果您的所有作业都是相同类型的(例如作业
List<Job<string>> x = new List<Job<string>>();
x.Add(new Job<string>());
但是,如果您想混合不同类型的作业(例如作业
public abstract class Job
{
// add whatever common, non-generic members you need here
}
public class Job<T> : Job
{
// add generic members here
}
然后你可以做:
List<Job> x = new List<Job>();
x.Add(new Job<string>());
如果希望在运行时获取作业的类型,可以执行以下操作:
Type jobType = x[0].GetType(); // Job<string>
Type paramType = jobType .GetGenericArguments()[0]; // string
通过创建接口并在类中实现它,您将能够创建该接口类型的列表,并添加任何作业:
interface IJob
{
//add some functionality if needed
}
public class Job<T> : IJob
{
public int ID { get; set; }
public Task<T> Task { get; set; }
public TimeSpan Interval { get; set; }
public bool Repeat { get; set; }
public DateTimeOffset NextExecutionTime { get; set; }
public Job<T> RunOnceAt(DateTimeOffset executionTime)
{
NextExecutionTime = executionTime;
Repeat = false;
return this;
}
}
List<IJob> x = new List<IJob>();
x.Add(new Job<string>());