简体   繁体   中英

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). They all have a field called TableName. I wanted to make a generic enumerator that is an extension method to a DataSet. The specific TableName would select which table in the DataSet to enumerate. 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.

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.

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:

[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});
    }
}

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