List of generic Type

前端 未结 2 1060
再見小時候
再見小時候 2021-01-01 20:19

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

Class

public class Job
{
    pub         


        
相关标签:
2条回答
  • 2021-01-01 20:41

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

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

    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
    
    0 讨论(0)
  • 2021-01-01 20:44

    By making an interface and implement it in your class you will be able to create a list of that interface type,adding any job :

    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>());
    
    0 讨论(0)
提交回复
热议问题