我是否需要在 WCF DataContract 中公开构造函数才能使其在客户端上的对象实例化期间工作?

发布于 2024-09-28 20:21:00 字数 624 浏览 0 评论 0原文

我在 WCF 服务中有一个类,我们称之为 AA 是一个数据协定,其中包含另一个自定义对象 B 的集合作为其数据成员之一。为了避免客户端出现空引用问题,我在构造函数中实例化 BList ,如下所示:

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

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

我的问题是,在客户端上,此实例化不会发生,并且出现 BList在客户端创建A对象后为null。我猜测构造函数不会出现在客户端上。那么,我需要让构造函数成为显式操作契约吗?如果是这样,那么客户就可以看到他们不应该看到的内部事物,对吧?我如何确保此实例化发生在客户端上?

谢谢,如果这看起来是个愚蠢的问题,我很抱歉。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

并安 2024-10-05 20:21:00

您需要使用 [OnDeserializing] 或 [OnDeserialized] 属性来对 DataContract 类型进行初始化。请参阅 http://msdn.microsoft.com/en-us/library/ms733734。 ASPX

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

墨落画卷 2024-10-05 20:21:00

我不确定是否有办法做到这一点,但通过从服务中获取新实例,应该初始化列表,我建议以下

  • 编写一个返回类的新实例的 Web 方法,您可以将其用作以下,我确信您的列表已初始化

要创建实例:

A a = new ServiceClient.CreateAInstance();

在服务中编写方法,

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

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();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文