Dot-Net
將 WCF 與抽像類一起使用
如何在 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; } }
我想到了。您需要使用“KnownType”在抽象基類上指定子類。解決方案是將其添加到 Foo 類中:
[DataContract] [KnownType(typeof(Bar))] // <------ added public abstract class Foo { [DataMember] public int Id { get; set; } [DataMember] public string BaseText { get; set; } }看看這個連結。