Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 546
Peter Trevor Avatar asked Feb 03 '26 21:02

Peter Trevor


1 Answers

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});
    }
}
like image 197
Mark Cidade Avatar answered Feb 05 '26 09:02

Mark Cidade



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!