本文介绍了将 WCF 与抽象类一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I define DataContract for abstract classes in WCF?

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

I have a class "Person" which I communicate successfully using WCF. Now I add a new class "Foo" referenced from Person. All still good. But when I make Foo abstract and define a sub class instead it fails. It fails on the server side with a CommunicationException, but that doesn't really tell me much.

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

My simplified classes made for testing:

[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; }
}

推荐答案

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

I figured it out. You need to specify the subclasses on the abstract base class using "KnownType". The solution would be to add this on the Foo class:

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

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

查看此链接.

这篇关于将 WCF 与抽象类一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 23:06
查看更多