问题
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