dimanche 25 octobre 2015

Using generics to return List of various types

Trying to get my head around generics and am wanting to create a class that returns records of various types.

So what I want is something like this:

public class Job
{
    public JobType Type { get; set; }

    public Job (JobType jobType)
    {
        Type = jobType;
    }

    public IList<T> GetRecords<T>()
    {
       IList<T> records = new IList<T>();

       if (Type == JobType.Type1)
       {
           List<Type1Record> records = GetType1Records();
       }
       if (Type == JobType.Type2)
       {
            List<Type2Record> records = GetType2Records();
       }
        return records;
    }
}

I would want to call this using something like

var job = new Job(JobType.Type1);

var jobRecords = Job.GetRecords();

I think the code above conveys the intention but I am beginning to think that I am going about this in the wrong way because the above just doesn't work at all. IList cannot be converted to other types like this.

Does anybody know how I can achieve something like this.

Aucun commentaire:

Enregistrer un commentaire