简体   繁体   中英

How to instantiate a class that has a Generic List and initialize the list at runtime without using dynamic or Reflection

Given classes that are like these, is there a way to instantiate the Employee class and initialize the Generic List at runtime. Company rules preclude me from using dynamic, and using Reflection is frowned upon, but if there is no other way I can use it.

class Employee
{   
    public void SetList<T>(List<T> list) where T : IInputRow<T>
    {
        InputRows = list;
    }

    public List<T> InputRows;
    public string EmployeeName {get; set;}
}
interface IInputRow<T>
{
    T Parse(DataRow dr);
}
class JobRow : IInputRow<JobRow>
{
    public int RowID {get; set;}
    public string RowName {get; set;}

    public JobRow Parse(DataRow dr)
    {
        //logic to convert datarow to entity
    }   
}
class VolunteerRow : IInputRow<VolunteerRow>
{
    public int VolunteerRowID {get; set;}
    public int VolunteerHours {get; set;}

    public VolunteerRow Parse(DataRow dr)
    {
        //logic to convert datarow to entity
    }
}

The list type has to be decided at run time.

I appreciate the comments and the answer, however, given that there are 46 different types of input rows I do not want to make the employee class generic as that would result in have to instantiate it for each input row that is needed for that round of processing. I might end up using reflection but I am somewhat hesitant about that given the sheer number of records that could conceivably be processed during a single run.

Try this Employee class:

public class Employee<T> where T : IInputRow<T>
{
    public List<T> list;
    public Employee()
    {
        list = new List<T>();
    }
}

The <T> after class name is the magic. When you want a new Employee class with a List<JobRow> , you say Employee<JobRow> j = new Employee<JobRow>(); .

Refer to Microsoft generic document for more info: https://docs.microsoft.com/en-us/dotnet/standard/generics/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM