通用类型列表 [英] List of generic Type

查看:51
本文介绍了通用类型列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通用类,我想创建一个列表.然后在运行时我得到了物品的类型

I have a generic class and I want to create a list of it. and then at run time I get the type of the item

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> ),则可以简单地创建该类型的列表:

If all of your jobs are of same type (e.g. Job<string>) you can simply create a list of that type:

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

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

However, if you want to mix jobs of different types (e.g. Job<string> and Job<int>) in the same list, you'll have to create a non-generic base class or interface:

public abstract class Job 
{
    // add whatever common, non-generic members you need here
}

public class Job<T> : Job 
{
    // add generic members here
}

然后您可以执行以下操作:

And then you can do:

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

如果您想在运行时获取 Job 的类型,可以执行以下操作:

If you wanted to get the type of a Job at run-time you can do this:

Type jobType = x[0].GetType();                       // Job<string>
Type paramType = jobType .GetGenericArguments()[0];  // string

这篇关于通用类型列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆