WCF 小程序案例以及序列化的使用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
//发布服务端的主机服务
string url = "http://localhost:8080";
ServiceHost sh = new ServiceHost(typeof(MyService));
Binding bind = new BasicHttpBinding();
sh.AddServiceEndpoint(typeof(IService), bind, url);
sh.Open();

//客户端发送消息,使用服务端的服务
ChannelFactory<IService> cf = new ChannelFactory<IService>(bind);
EndpointAddress ea = new EndpointAddress(url);
IService iservice = cf.CreateChannel(ea);
Student ss = iservice.GetStudent();
Console.WriteLine(ss.StuID);
Console.WriteLine(ss.Name);
Console.WriteLine(ss.Age);
Console.Read();
}
}

/// <summary>
/// 定义服务的协定接口
/// </summary>
[ServiceContract]
public interface IService
{
[OperationContract]
Student GetStudent();
}

/// <summary>
/// 实现服务接口
/// </summary>
public class MyService : IService
{
public Student GetStudent()
{
Student s = new Student();
s.StuID = 123456;
s.Name = "哈哈哈哈";
s.Age = 20;
return s;
}
}

/// <summary>
/// 序列化
/// </summary>
[DataContract]
public class Student
{
private long stuID;
[DataMember]
public long StuID
{
get { return stuID; }
set { stuID = value; }
}

private string name;
[DataMember]
public string Name
{
get { return name; }
set { name = value; }
}

private int age;
[DataMember]
public int Age
{
get { return age; }
set { age = value; }
}

/// <summary>
/// 反序列化时,执行此方法
/// </summary>
/// <param name="ss"></param>
[OnSerializing]
public void hhha(StreamingContext ss)
{
this.Age = this.Age == 20 ? 50 : 88;
}

}


}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值