【问题标题】:Deserialize Abstract Class反序列化抽象类
【发布时间】:2010-10-12 15:40:12
【问题描述】:

我有一个抽象类“服务器”,我在我的 UI 中的 JavaScript 中创建它,然后我想在我的 Web 服务上有一个方法,它执行以下操作:

public List<Database> GetDatabases(Server server)
{
    Type type = server.GetType();
    Server x = null;

    if (typeof (SqlServer2005Server).Equals(type))
    {
        x = new SqlServer2005Server();
    }

    // Return the Databases from the server
    return x.GetDatabases();
}

我遇到的问题是服务器不能被反序列化,因为它是抽象的,我是否需要为我拥有的每个服务器都有一个从具体类型继承的方法,即

public List<Database> GetDatabases(SqlServer2005Server server)
{
    // Return the Databases from the server
    return SqlServer2005Serverx.GetDatabases();
}

public List<Database> GetDatabases(OracleServer server)
{
    // Return the Databases from the server
    return SqlServer2005Serverx.GetDatabases();
}

非常感谢您的帮助,因为我不确定什么是最好的解决方案

我收到的确切错误是:

无法创建抽象类的实例。

【问题讨论】:

    标签: c# .net wcf exception-handling abstract-class


    【解决方案1】:

    WCF 将支持继承,但您需要使用已知类型属性来装饰您的数据协定。例如:

    [DataContract]
    [KnownType(typeof(Customer))]
    class Contact
    {
       [DataMember]
       public string FirstName
       {get;set;}
    
       [DataMember]
       public string LastName
       {get;set;}
    }
    [DataContract]
    class Customer : Contact
    {
       [DataMember]
       public int OrderNumber
       {get;set;}
    }
    

    HTH。

    【讨论】:

    • 感谢您的回复,我可以添加几个KnowTypes。即 [DataContract] [KnownType(typeof(Customer))] [KnownType(typeof(Employee))] [KnownType(typeof(Alien))] class Contact { ... 非常感谢 Phill
    • 这是否也适用于抽象类,我可以在您的示例中看到它是一个普通类?再次感谢菲尔
    • 嗨,Phil,如果您需要,您可以根据需要添加任意数量的 KnownType 属性。一切都取决于您的继承链的深度。 HTH。祝你好运。
    • 感谢史蒂夫的回复,我仍然不知道如何让它与抽象类一起使用,我认为这是我的问题,因为我尝试了您提供的解决方案无济于事(它将来肯定会有所帮助)。非常感谢您的帮助!
    • 嗨菲尔,没问题。请记住,这用于继承层次结构。您可能需要做的是重构您的代码并创建一个具有 SQL 和 Oracle 专业化的基础数据库类。你可以有效地完成同样的事情。祝你好运! :)
    猜你喜欢
    • 2017-11-06
    • 2012-11-18
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-07
    相关资源
    最近更新 更多