Do I need to expose a constructor in a WCF DataContract for it to work during object instantiation on the client?

落花浮王杯 提交于 2019-12-22 04:11:55

问题


I have a class in a WCF service, lets call it A. A is a data contract, which contains as one of its DataMembers a collection of another custom object B. To avoid Null Reference problems on the client side, I instantiate the BList in the constructor like so:

[DataContract]
public class A
{
    [DataMember]
    public String name { get; set; }
    [DataMember]
    public List<B> BList {get; set; }

    public A()
    {
        BList = new List<B>();  
    }
}

My problem is that on the client, this instantiation does not happen and BList appears as null after an object of A is created on the client. I'm guessing that the constructor does not appear on the client. So, do I need to make the constructor an explicit operation contract? If so that would make internal things visible to the client that they shouldn't see, right? How do I make sure that this instantiation happens on the client?

Thanks, and sorry if this seems like a dumb question.


回答1:


You need to use [OnDeserializing] or [OnDeserialized] attributes to do initialization of DataContract types. See http://msdn.microsoft.com/en-us/library/ms733734.aspx




回答2:


I am not sure if there is a way to do this but by getting the new instance from the service the list should be initialized, I suggest the following

  • Write a web method that returns a new instance of your class and you might use it as the following and I am sure your list is initialized

To create the instance:

A a = new ServiceClient.CreateAInstance();

In the service write the method,

[OperationContract]
public A CreateAInstance()
{
     return new A();
}


来源:https://stackoverflow.com/questions/4019354/do-i-need-to-expose-a-constructor-in-a-wcf-datacontract-for-it-to-work-during-ob

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!