【问题标题】:Casting DataRow to Strongly-Typed DataRow: How do they do it?将 DataRow 转换为强类型 DataRow:他们是如何做到的?
【发布时间】:2011-11-30 07:52:13
【问题描述】:

我正在尝试制作一些强类型 DataRows 的轻量级版本,以便为采用 IEnumerable<T> where T : DataRow 的方法编写测试。

我想创建一个继承自DataRow 但具有其他属性的类,如自动生成的强类型 DataSet.Designer.cs 中。我无法让他们的代码工作,而且我确实不明白它是如何工作的:

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

每次我尝试模拟运行时 - 我都会收到 InvalidCastException(无法将 System.DataRow 类型的对象转换为 AnimalRow 类型)。正如我所料。

那么是什么让他们的代码更特别?

【问题讨论】:

  • 你的数据表是什么?和动物数据表?还是普通的香草数据表?以上依赖于覆盖的NewRow等。
  • 也...键入的数据表.... YMMV,但 IMO(非常主观)您应该尝试在这里只使用常规类。
  • ... Designer.cs 不包含任何对 NewRow 的覆盖。你认为我应该上传整个自动生成的文件吗?我认为没有人会对此有耐心。
  • 我正在测试一种采用IEnumerable<T> where T : DataRow 的方法。 IE,对方法没有敏感。我很想把所有的 DataTables 和他们的同胞踢出代码库。没办法。
  • @sq33G 请不要(全部上传)。我已经真的 很长时间没有使用过类型化的数据表了,但我确定某处里面有一条与 AnimalRow 相关的行——可能是通过 typeof(.. .)

标签: c# casting strongly-typed-dataset auto-generate


【解决方案1】:

感谢@Marc Gravell 将其引向正确的方向:

AnimalDataTable 类包含两个对 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    相关资源
    最近更新 更多