[英]Serialize delivered class's instance using DataContract
I have library with class in it looks like next: 我有类的图书馆看起来像下一个:
[DataContract]
class MyBaseClass
{
public string Name { get; set; }
}
Also, I have another project with ref of this library and class in it looks like: 另外,我还有另一个引用此库和类的项目,如下所示:
[DataContract]
class MyDeliveredClass : MyBaseClass
{
public string SecondName { get; set; }
}
I wonder how could I serialize list<MyBaseClass>
which could contain objects of MyBaseClass
and MyDeliveredClass
? 我想知道如何序列化可能包含
MyBaseClass
和MyDeliveredClass
对象的list<MyBaseClass>
?
May be I should use [KnownType(MyDeliveredClass)]
... but I have no reference to MyDeliveredClass
in library... 也许我应该使用
[KnownType(MyDeliveredClass)]
...但是我没有在库中引用MyDeliveredClass
...
If you declare both MyBaseClass and MyDeliveredClass as Service known types on the service contract interface then that should do the trick: 如果在服务协定接口上将MyBaseClass和MyDeliveredClass都声明为Service已知类型,则应该可以做到这一点:
[ServiceContract(SessionMode = SessionMode.Required, ...)]
[ServiceKnownType(typeof(MyBaseClass ))]
[ServiceKnownType(typeof(MyDeliveredClass ))]
public interface IMySerivceContract {
...
}
Generally you have to choice between delclaring as KnownTypes on the class declaration or as ServerKnownTypes on the service interface. 通常,您必须在在类声明上声明为KnownTypes或在服务接口上声明为ServerKnownTypes之间进行选择。 However sometimes the KnownType route is not an option for various reasons - one of which is your situation where you dont have access to a class declaration.
但是,有时由于各种原因,不是KnownType路由的选项-其中之一就是您无法访问类声明的情况。 Another case where you are forced to use ServiceKnownTypes is if your contract uses interfaces instead of the base class ie if your contract had
List<IMyBaseInterface>
. 另一种被迫使用ServiceKnownTypes的情况是,如果您的合同使用接口而不是基类,即您的合同具有
List<IMyBaseInterface>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.