Casting DataRow to Strongly-Typed DataRow: How do they do it?

拜拜、爱过 提交于 2019-12-24 06:40:13

问题


I'm trying to make a lightweight version of some strongly-typed DataRows in order to write a test for a method that takes IEnumerable<T> where T : DataRow.

I would like to make a class that inherits from DataRow but has additional properties, as in the autogenerated strongly-typed DataSet.Designer.cs. I cannot get their code to work, and indeed I don't understand how it could work:

// from AnimalDataSet.Designer.cs:
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public AnimalRow AddAnimalRow(
        string Name, 
        int Species_ID) {
    AnimalRow rowAnimalRow = ((AnimalRow)(this.NewRow()));
    object[] columnValuesArray = new object[] {
        null,
        Name,
        Species_ID};
    rowAnimalRow.ItemArray = columnValuesArray;
    this.Rows.Add(rowAnimalRow);
    return rowAnimalRow;
}

Every time I try to run an imitation of this - I get InvalidCastException (Unable to cast object of type System.DataRow to type AnimalRow). As I would have expected.

So what makes their code more special?


回答1:


Credit to @Marc Gravell for steering this in the right direction:

The AnimalDataTable class contains two overrides of undocumented* virtual methods of DataTable:

[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override global::System.Data.DataRow NewRowFromBuilder(global::System.Data.DataRowBuilder builder) {
    return new AnimalRow(builder);
}

[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override global::System.Type GetRowType() {
    return typeof(AnimalRow);
}

*mostly undocumented



来源:https://stackoverflow.com/questions/8322679/casting-datarow-to-strongly-typed-datarow-how-do-they-do-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!