-1
public class MyDataTable : DataTable
{
    public string MyProperty { get; set; }
    public DataTable MyData { get; set; }

    public void MyMethod()
    {
        //...do some processing on itself
        MyData = this;
    }
}

我创建了这个继承 DataTable 的 MyDataTable 类。

public class MyClass
{
    public void ProcessData()
    {
        MyDataTable table = new MyDataTable();
        table.MyMethod();

        AcceptDataTable(table); //it won't accept the table parameter.
        AcceptDataTable(table.MyData); //it still won't accept the table parameter.
        AcceptDataTable((DataTable)table); //it still won't accept the table parameter.
    }

    public void AcceptDataTable(DataTable table)
    {
        Service1.SubmitData(table); //actually this is where it fails. It is a WCF Service's method that takes a DataTable as parameter. It works fine if I pass a DataTable, but not MyDataTable
    //There was an error while trying to serialize parameter http://tempuri.org/:dt. The InnerException message was 'Type 'SubmitData' with data contract name MyDataTable
    }
}
4

1 回答 1

-1

为什么要扩展 DataTable?如果您正在寻找添加方法,您应该查看Extension Methods。我很确定DataTable 类没有任何可以覆盖的虚拟方法或属性,并且成员隐藏在polymorphism中不起作用。 查看这篇文章,了解另一个试图扩展 DataTable 的人的观点。

编辑:

如果您还尝试通过 WCF 传递您的对象,则必须将其标记为Serializable,但这会导致一些其他时髦的问题,并且如果基类具有某种特殊的序列化,则可能会被拒绝。在这种情况下,将派生类标记为 [Serializable] 也会引发错误。

我会根据您的描述认真考虑工厂模式。这样你就有了你的工厂类,它每次都按照你的需要构建你的表,但它仍然是一个 DataTable。

如果数据表中有任何对象(不是原始对象),则必须将 WCF 服务标记为具有“KnownTypes(typeof(MyType))”,以便它知道在序列化数据表中存在序列化的内容。

最后一次抽签,您应该避免在 WCF 中使用数据表和数据集...

从 Web 服务返回数据集是撒旦的产物,代表了世界上真正邪恶的一切

使用数据集的 WCF 性能 - 第 2 部分

于 2012-10-01T19:39:41.480 回答