将WCF与抽象类一起使用

时间:2010-06-23 12:54:17

标签: .net wcf abstract-class datacontract

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

我有一个类“Person”,我使用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; }
}

2 个答案:

答案 0 :(得分:33)

我明白了。您需要使用“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

答案 1 :(得分:2)

有趣。

我希望代码在Person构造函数中失败,因为您无法直接实例化Abstract Class。