23.2.1 设计与实现服务契约(2)
【代码解析】在服务契约中定义了加、减、乘、除和百分比这5种服务方法,通过这5种服务方法可以实现相关的服务操作。
(6)修改Service1.cs文件中的程序代码,用于具体实现加、减、乘、除和百分比这5种操作,修改后Service1.cs文件中的程序代码如下:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Runtime.Serialization;
- using System.ServiceModel;
- using System.Text;
- namespace WcfServiceLibrary1
- {
- //注意:如果更改此处的类名IService1,则必须更新 App.config 中对IService1的引用
- public class Service1 : IService1
- {
- //加法运算
- public double Add(double a1,double a2)
- {
- return a1 + a2;
- }
- //减法运算
- public double Subtract(double a1, double a2)
- {
- return a1 - a2;
- }
- //乘法运算
- public double Multiply(double a1, double a2)
- {
- return a1 * a2;
- }
- //除法运算
- public double Divide(double a1, double a2)
- {
- return a1 / a2;
- }
- //百分比
- public double Percent(double a1, double a2)
- {
- return (a1 / a2)*100;
- }
- public string GetData(int value)
- {
- return string.Format("You entered: {0}", value); //返回格式化后的数据
- }
- public CompositeType GetDataUsingDataContract(CompositeType composite)
- {
- if (composite.BoolValue)
- {
- composite.StringValue += "Suffix";
- }
- return composite; //返回数据信息
- }
- }
- }
【代码解析】代码中通过定义的Add()、Subtract()、Multiply()和Divide()这4个函数,分别实现加、减、乘、除这4种数学运算。
到此为止,服务契约和实现类就创建完成了,从而完成了定义整个WCF服务的操作。