WCF DataContract 中的构造函数未反映在客户端上 [英] Constructor in WCF DataContract not reflected on Client

查看:23
本文介绍了WCF DataContract 中的构造函数未反映在客户端上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在客户端创建 DataContract 的实例时,我需要让一些数据成员获得一些值.使用构造函数不会发生这种情况.我搜索了不同的论坛,发现我们必须使用 [OnDeserializing] 和 [OnDeserialized] 属性.这也行不通.有人可以在这里提出建议.另一种选择是在客户端的部分类中创建构造函数.我想避免这种情况.

I need to have some data members get some values when I create an instance of the DataContract on the client. This is not happening using constructors. I have searched through different forums and found we have to use [OnDeserializing] and [OnDeserialized] attributes. This is also not working. Can somebody suggest something here. The other alternative is creating constructors in the partial classes at the client side. I want to avoid that.

请在下面找到代码:

服务端:数据合约

[DataContract]
public class Account
{

    private int mAccountId;
    private string mAccountName;

    public Account()
    {
        mAccountId = 5;
        mAccountName = "ABC";
    }

    [OnDeserializing]
    public void OnDeserializing(StreamingContext context)
    {
        mAccountId = 5;
        mAccountName = "ABC"; 
    }

    [OnDeserialized]
    public void OnDeserialized(StreamingContext context) 
    {

    } 

    [DataMember]
    public int AccountId
    {
        get
        {
            return mAccountId;
        }
        set
        {
            mAccountId = value;
        }
    }

    [DataMember]
    public string AccountName
    {
        get
        {
            return mAccountName;
        }
        set
        {
            mAccountName = value;
        }
    }


}

客户端 - 初始化

namespace TestClient
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Account acc = new Account();

        }
    }
}

推荐答案

用于创建 WCF 代理类的代码生成器创建兼容的协定类型,并且不使用与 WCF 服务使用的完全相同的类型.实现您想要的最简单的方法是在您的客户端上自己创建构造函数,因为生成的代码是 partial:

The code generator used to create WCF proxy classes creates compatible contract types, and doesn't used the exact same type as used by the WCF service. The easiest way to achieve what you want, is to create the constructor yourself on your client, as the code generated is partial:

partial class Account
{
    public Account()
    {
        AcountId = 5;
        AccountName = "ABC";
    }
}

如果您不想这样做,您可以让 WCF 重用您的客户端项目已经引用的类型.因此,如果您的数据协定类位于单独的库中(如推荐),您可以引用该库,然后重新配置 WCF 客户端项目以重用引用程序集中的共享类型.

If you don't want to do this, you can get WCF to reuse types that are already referenced by your client project. So if your data contract classes are in a separate library (as is recommended), you can reference that library and then reconfigure your WCF client project to reuse the shared types from the referenced assembly.

这篇关于WCF DataContract 中的构造函数未反映在客户端上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆