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

查看:78
本文介绍了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代理类的代码生成器创建兼容的合同类型,并且没有使用与W​​CF服务完全相同的类型.实现所需目标的最简单方法是在客户端上自行创建构造函数,因为生成的代码为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天全站免登陆