簡體   English   中英

泛型和繼承

[英]Generics and inheritance

這里有兩個問題......

我有一組DataRow包裝器(在VS2008中)繼承自基類(稱為RecordBase)。 它們都有一個名為TableName的字段。 我想創建一個通用的枚舉器,它是DataSet的擴展方法。 特定的TableName將選擇要枚舉的DataSet中的哪個表。 我想寫

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

問題1:我找不到一種方法來擁有一個可重寫的靜態字段,迫使我創建一個包裝器的虛擬實例來獲取TableName。

問題2:不太嚴重,即使包裝器(和基座)有一個接受DataRow的構造函數,編譯器仍然堅持使用無參數構造函數約束。

所有這些都讓我看起來像代碼

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

有任何想法嗎?

您可以使用表名的自定義屬性和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