简体   繁体   English

为什么我的对象不需要ServiceKnownType?

[英]Why is ServiceKnownType not needed for my object?

It is my understanding that every type (other than some primitives like int and string) used in a WCF ServiceContract need to be declared with ServiceKnownType attribute. 据我了解,在WCF ServiceContract中使用的每种类型(除了某些诸如int和string之类的原语之外)都需要使用ServiceKnownType属性进行声明。 But, I have build a custom object and it is transmitted accross my WCF service with no problem -- even though I have not added a ServiceKnownType for it. 但是,我已经构建了一个自定义对象,并且即使没有为它添加ServiceKnownType,它也可以毫无问题地在我的WCF服务中传输。 Will someone please explain why this works? 有人能解释一下为什么行吗?

[ServiceContract(CallbackContract = typeof(IMyServiceCallback))]
public interface IMyService
{
    [OperationContract]
    List<MyObject> LoadMyObjects();
}

[DataContract]
public class MyObject
{
    [DataMember]
    private int batchID;
    [DataMember]
    private int fileID;
    [DataMember]
    private string fileName;
    [DataMember]
    private DateTime importStartTime;
// ...
}

No it is not correct. 不,这是不正确的。 ServiceKnownType (or KnownTypeAttribute on data contract) is only needed for types used by the service but not specified in operation definition. ServiceKnownType(或数据协定上的KnownTypeAttribute)仅对于服务使用的类型才需要,但在操作定义中未指定。 In your case you have defined LoadMyObjects operation which uses MyObject class. 在您的情况下,您已定义了使用MyObject类的LoadMyObjects操作。 Because the operation directly uses MyObject you don't have to add MyObject as ServicKnownType. 因为该操作直接使用MyObject,所以不必将MyObject添加为ServicKnownType。 But if you define MyObject2 derived from MyObject you will not be able to send that object from LoadMyObjects operation until you declare MyObject2 as ServiceKnownType. 但是,如果您定义派生自MyObject的MyObject2,则除非将MyObject2声明为ServiceKnownType,否则将无法通过LoadMyObjects操作发送该对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM