通用类型列表

时间:2013-07-30 22:54:57

标签: c# generics

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

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
}

2 个答案:

答案 0 :(得分:26)

如果您的所有工作都属于同一类型(例如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

答案 1 :(得分:4)

通过创建一个接口并在您的类中实现它,您将能够创建该接口类型的列表,添加任何作业:

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