通用类使用新关键字创建

时间:2018-04-02 07:22:24

标签: c# class generics

我上课了。就像那样;

    public class AlarmSeverityDto
{
    private readonly DataRow _dr;

    public object this[string columnname] { get { return _dr[columnname]; } }
    public string Id { get { return Convert.ToString((_dr["Id"])); } }

    public string Description { get { return Convert.ToString((_dr["Description"])); } }

    public AlarmSeverityDto(DataRow dr)
    {
        _dr = dr;
    }
}

我像这样使用这个类;

    public List<AlarmSeverityDto> GetAlarmSeverityDtos()
    {
        var resultList = new List<AlarmSeverityDto>();
        var dataSet = new DataSet();
        using (OdbcConnection connection = new OdbcConnection(_szConn))
        {
            var query = string.Format("SELECT Id, Description " +
                                      "FROM  tblAlarmSeverityType");

            OdbcDataAdapter adapter = new OdbcDataAdapter(query, connection);
            try
            {
                connection.Open();
                adapter.Fill(dataSet);
                if (dataSet.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow hbrow in dataSet.Tables[0].Rows)
                    {
                        var alarmSeverityDto = new AlarmSeverityDto(hbrow);
                        resultList.Add(alarmSeverityDto);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        return resultList;
    }

我想制作通用的GetAlarmSeverityDtos。但我不能用泛型做到这一点。我试过,但我不能做一行。我的Generic类就是这样;

 public List<T> GetDataTable<T>(string query) where T : class,new()

但是我应该为这条线做什么呢?

var alarmSeverityDto = new AlarmSeverityDto(hbrow);

如何用泛型类编写这一行?

2 个答案:

答案 0 :(得分:2)

您可以使用Activator.CreateInstance

或者另一种方式(根据您的需要),您可以使用界面

public interface IMyAwesomeInterface
{
    DataRow DataRow { get; set; }
}

...

public class AlarmSeverityDto : IMyAwesomeInterface

...

public List<T> GetAlarmSeverityDtos<T>() where T : IMyAwesomeInterface, new()
{
    ...
    var alarmSeverityDto = new T() { DataRow = hbrow};

    resultList.Add(alarmSeverityDto);
    ...
}

答案 1 :(得分:0)

您可以传入一个工厂函数,该函数指定如何将数据行转换为T.例如:

public List<T> GetDataTable<T>(string query, Func<DataRow, T> factory )

然后在GetDataTable中,通过调用回调来创建实例:

T record = factory(hbrow);

最后,可以通过传递回调来调用GetDataTable。 E.g:

List<AlarmSeverityDto> result = GetDataTable<AlarmSeverityDto>( query, 
row => new AlarmSeverityDto(row) );

这允许类型变量为任何类型,而无需支持特定接口,也不必依赖运行时激活服务。

相关问题