22

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

我有一个“人”类,我使用 WCF 成功通信。现在我添加一个从 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; }
}
4

2 回答 2

34

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

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

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

看看这个链接

于 2010-06-23T13:01:43.817 回答
2

有趣的。

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

于 2010-06-23T12:59:59.313 回答