【问题标题】:Using WCF with abstract classes将 WCF 与抽象类一起使用
【发布时间】:2011-03-07 07:36:03
【问题描述】:

如何在 WCF 中为抽象类定义 DataContract?

我有一个使用 WCF 成功通信的“Person”类。现在我添加一个从 Person 引用的新类“Foo”。一切都还好。但是当我使 Foo 抽象并定义一个子类时,它会失败。它在服务器端失败并出现 CommunicationException,但这并不能告诉我太多。

我为测试而制作的简化类:

[DataContract]
public class Person
{
    public Person()
    {
        SomeFoo = new Bar { Id = 7, BaseText = "base", SubText = "sub" };
    }

    [DataMember]
    public int Id { get; set; }

    [DataMember]
    public Foo SomeFoo { get; set; }
}

[DataContract]
public abstract class Foo
{
    [DataMember]
    public int Id { get; set; }

    [DataMember]
    public string BaseText { get; set; }
}

[DataContract]
public class Bar : Foo
{
    [DataMember]
    public string SubText { get; set; }
}

【问题讨论】:

    标签: .net wcf abstract-class datacontract


    【解决方案1】:

    我想通了。您需要使用“KnownType”在抽象基类上指定子类。解决方案是将其添加到 Foo 类中:

    [DataContract]
    [KnownType(typeof(Bar))] // <------ added
    public abstract class Foo
    {
        [DataMember]
        public int Id { get; set; }
    
        [DataMember]
        public string BaseText { get; set; }
    }
    

    查看this link

    【讨论】:

    • 完美。非常感谢!
    【解决方案2】:

    有趣。

    我希望代码在 Person 构造函数中失败,因为您不能直接实例化抽象类。

    【讨论】:

    • 好点。这可能是它失败的原因?虽然找到了解决方案。看看我自己的答案..
    猜你喜欢
    • 1970-01-01
    • 2020-10-06
    • 1970-01-01
    • 2021-08-21
    • 2011-02-13
    • 2020-12-30
    • 2018-10-06
    • 2020-02-13
    • 1970-01-01
    相关资源
    最近更新 更多