泛型类型列表

本文关键字:列表 泛型类型 | 更新日期: 2023-09-27 18:25:38

我有一个泛型类,我想创建它的列表。然后在运行时,我得到项目的类型

类别

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
}

泛型类型列表

如果您的所有作业都属于同一类型(例如Job<string>),您可以简单地创建该类型的列表:

List<Job<string>> x = new List<Job<string>>();
x.Add(new Job<string>());

但是,如果您想在同一列表中混合不同类型的作业(例如Job<string>Job<int>),则必须创建一个非通用基类或接口:

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>());

如果你想在运行时获得Job的类型,你可以这样做:

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>());