如何在C#中使用datacontract?

How to use datacontract in C#?

我在服务器端和客户端都有这个接口:

namespace BH_Server {
    [ServiceContract]
    public interface BHInterface {
        [OperationContract]
        string GetName( string name );
        [OperationContract]
        Device GetDevice();
    }
    [DataContract]
    public class Device {
        private string dSN;
        [DataMember]
        public string SN {
            get { return dSN; }
            set { dSN = value; }
        }
    }
}

此外,我在服务器端有这个:

public class CronServiceInterface : BHInterface {
  public string GetName( string name ) {
        return string.Format( "Hello {0}", name );
  }
  public Device GetDevice() {
        Device d = new Device();
        d.SN = "123456789";
        return d;
    }
}

在服务器端,还有:

host = new ServiceHost( typeof( CronServiceInterface ), new Uri[] {
    new Uri("net.pipe://localhost/")
} );
host.AddServiceEndpoint( typeof( BHInterface ), new NetNamedPipeBinding( NetNamedPipeSecurityMode.None ), "BhPipe" );
host.Open();

要在客户端创建连接,使用以下代码:

NetNamedPipeBinding binding = new NetNamedPipeBinding( NetNamedPipeSecurityMode.None );
ChannelFactory<BHInterface> channelFactory = new ChannelFactory<BHInterface>( binding );
EndpointAddress endpointAddress = new EndpointAddress( "net.pipe://localhost/BhPipe/" );
BHInterface iface = channelFactory.CreateChannel( endpointAddress );

这里显然没有写完所有的代码,希望看到实现的内容就够了

在客户端使用 Debug.WriteLine( iface.GetName("Tom") ); 结果 "Hello Tom",但以下代码不起作用:

Device d;
d = iface.GetDevice();
Debug.WriteLine( string.Format( "Printing sn: {0}", d.SN ) );

它打印:"Printing sn: ".

我使用的是 .NET 4.5,没有出现错误。我是 WCF 主题的新手。

有人可以向我解释一下如何将所需的对象传递给客户吗?

要解决此问题,只需删除 属性 的支持字段并将 DataContract 定义为

[DataContract]
public class Device {
    [DataMember]
    public string SN {get;set;}
}

原因是 dSN 的值没有从服务发送到客户端,因为它不是 [DataMember]。其他解决方案是使用 [DataMember] 属性标记私有字段,但您通常应避免这种做法。

此外,请记住在对数据合同进行任何更改后更新服务参考,否则客户仍会看到旧合同。

详细说明...就像 ServiceContract 和 OperationContract 显示原型 veses 实现一样,DataContract 和 DataMembers 也是如此。您正在实施

get { return dSN; }
set { dSN = value; }

所需要的只是

public string SN {get;set;}

咦,我发现了!

我不得不在我的数据合同中使用属性!

namespace BH_Server {
    [ServiceContract]
    public interface BHInterface {
        [OperationContract]
        string GetName( string name );
        [OperationContract]
        Device GetDevice();
    }
    [DataContract( Name = "Device", Namespace = "" )]
    public class Device {

        [DataMember( Name = "SN", Order = 1 )]
        public string SN { get; set; }
    }
}

现在它就像一个魅力!