使用WCF与抽象类抽象类、WCF

2023-09-03 12:30:40 作者:余生请指教

如何定义DataContract为抽象类的WCF?

我有一类人,我使用WCF成功通信。现在,我想补充一个新的类富的人引用。一切尚好。但是,当我做美孚抽象,定义一个子类,而不是失败。它无法与一个在的CommunicationException服务器端,但并没有真正告诉我了。

所规定的试验

我的简单类:

  [DataContract]
公共类Person
{
    公众人物()
    {
        SomeFoo =新的酒吧{n = 7,BaseText =基地,潜台词=亚健康};
    }

    [数据成员]
    公众诠释编号{获得;组; }

    [数据成员]
    公共富SomeFoo {获得;组; }
}

[DataContract]
公共抽象类Foo
{
    [数据成员]
    公众诠释编号{获得;组; }

    [数据成员]
    公共字符串BaseText {获得;组; }
}

[DataContract]
公共类酒吧:美孚
{
    [数据成员]
    公共字符串的潜台词{获得;组; }
}
 

解决方案

我想它了。你需要指定使用KnownType的抽象基类的子类。解决的办法是添加这对Foo类:

  [DataContract]
[KnownType(typeof运算(酒吧))] //< ------添加
公共抽象类Foo
{
    [数据成员]
    公众诠释编号{获得;组; }

    [数据成员]
    公共字符串BaseText {获得;组; }
}
 

查看此链接。

PHP教程之关键字及抽象类使用总结的详细资料说明

How do I define DataContract for abstract classes in WCF?

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

解决方案

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

Check out this link.