简体   繁体   English

如何实例化具有通用列表的 class 并在运行时初始化列表而不使用动态或反射

[英]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.给定这样的类,有没有办法实例化 Employee class 并在运行时初始化通用列表。 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.我很欣赏评论和答案,但是,鉴于有 46 种不同类型的输入行,我不想让员工 class 通用,因为这将导致必须为该轮所需的每个输入行实例化它加工。 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:试试这个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. class 名称之后的<T>具有魔力。 When you want a new Employee class with a List<JobRow> , you say Employee<JobRow> j = new Employee<JobRow>();当您想要一个带有List<JobRow>的新Employee class 时,您可以说Employee<JobRow> j = new Employee<JobRow>(); . .

Refer to Microsoft generic document for more info: https://docs.microsoft.com/en-us/dotnet/standard/generics/有关详细信息,请参阅 Microsoft 通用文档: https://docs.microsoft.com/en-us/dotnet/standard/generics/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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