简体   繁体   English

泛型和继承

[英]Generics and inheritance

Two problems in one here ... 这里有两个问题......

I have a set of DataRow wrappers (in VS2008) that inherit from a base class (called RecordBase). 我有一组DataRow包装器(在VS2008中)继承自基类(称为RecordBase)。 They all have a field called TableName. 它们都有一个名为TableName的字段。 I wanted to make a generic enumerator that is an extension method to a DataSet. 我想创建一个通用的枚举器,它是DataSet的扩展方法。 The specific TableName would select which table in the DataSet to enumerate. 特定的TableName将选择要枚举的DataSet中的哪个表。 I'd like to write 我想写

public static IEnumerable<T> GetRecords<T>(this DataSet MySet) where T : RecordBase
{
    foreach (DataRow row in MySet.Tables[T.TableName].Rows)
    {
        yield return new T(row);
    }
}

Problem 1: I can't find a way to have an overrideable static field, forcing me to create a dummy instance of the wrapper just to get the TableName. 问题1:我找不到一种方法来拥有一个可重写的静态字段,迫使我创建一个包装器的虚拟实例来获取TableName。

Problem 2: Less serious, even though the wrappers (and the base) have a constructor that accepts a DataRow the compiler still insists that I use the parameterless constructor constraint. 问题2:不太严重,即使包装器(和基座)有一个接受DataRow的构造函数,编译器仍然坚持使用无参数构造函数约束。

All of which leaves me with code looking like 所有这些都让我看起来像代码

public static IEnumerable<T> GetRecords<T>(this DataSet MySet) where T : RecordBase, new()
{
    string TableName = (new T()).TableName;

    foreach (DataRow row in MySet.Tables[TableName].Rows)
    {
        T record = new T();
        record.RowData = row;
        yield return record;
    }
}

Any ideas? 有任何想法吗?

You can use an custom attribute for the table name and Activator to instantiate the type: 您可以使用表名的自定义属性和Activator来实例化类型:

[Table("Customers")]
class Customer : RecordBase { }

//...
public static IEnumerable<T> GetRecords<T>(this DataSet MySet) where T : RecordBase
{
    var attribT = typeof(TableAttribute);
    var attrib  = (TableAttribute) typeof(T).GetCustomAttributes(attribT,false)[0];

    foreach (DataRow row in MySet.Tables[attrib.TableName].Rows)
    {
        yield return (T) Activator.CreateInstance(typeof(T),new[]{row});
    }
}

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

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