WCF数据协定

今天还是按部就班的开始在MSDN里面翻找WCF的资料。先从定义开始吧。

看着下面这些代码,我貌似发现一个东西,那就是带有[DataMember]标签的方法都是可以给客户端开放使用的,不带有的客户端就不给用,好像就是这样的。

[DataContract(Namespace="http://Microsoft.ServiceModel.Samples")]
internal class Record
{
private double n1;
private double n2;
private string operation;
private double result;

internal Record(double n1, double n2, string operation, double result)
{
this.n1 = n1;
this.n2 = n2;
this.operation = operation;
this.result = result;
}

[DataMember]
internal double OperandNumberOne
{
get { return n1; }
set { n1 = value; }
}

[DataMember]
internal double OperandNumberTwo
{
get { return n2; }
set { n2 = value; }
}

[DataMember]
internal string Operation
{
get { return operation; }
set { operation = value; }
}

[DataMember]
internal double Result
{
get { return result; }
set { result = value; }
}

public override string ToString()
{
return string.Format("Record: {0} {1} {2} = {3}", n1, operation, n2, result);
}
}

在辗转反侧的时候,看到一个使用不同的编写器来影响XML的编码。这个技术貌似就是接下来我需要的东西。通过把文本格式写成二进制可以大量减少长度,增加传输时候的稳定性。

1 //声明一个内存流对象
2  MemoryStream stream2 = new MemoryStream();
3  //使用一个二进制的编写器来影响XML的编码流
4 XmlDictionaryWriter binaryDictionaryWriter = XmlDictionaryWriter.CreateBinaryWriter(stream2);
5 //在序列化对象中通过使用二进制编写器来装载一个数据实例
6 serializer.WriteObject(binaryDictionaryWriter, record1);
7 binaryDictionaryWriter.Flush();
8
9 //流的长度比较
10 Console.WriteLine("Text Stream is {0} bytes long", stream1.Length);
11 Console.WriteLine("Binary Stream is {0} bytes long", stream2.Length);

数据的派生也是可以在这里运用的,不过代码看着怪累的。好了。我贴好这断休息一下了。

1 //继承了父类的构造函数并且增添了新的一个数据
2 //但是语言是不是不严谨,太随意了。
3 [DataContract(Namespace="http://Microsoft.ServiceModel.Samples")]
4 public class ComplexNumberWithMagnitude : ComplexNumber
5 {
6 public ComplexNumberWithMagnitude(double real, double imaginary) : base(real, imaginary) { }
7
8 [DataMember]
9 public double Magnitude
10 {
11 get { return Math.Sqrt(Imaginary*Imaginary + Real*Real); }
12 set { throw new NotImplementedException(); }
13 }
14 }

好了。我得休息一下了。脑袋发涨了。

注意:所有的代码都是来自MSDN。

原文地址:https://www.cnblogs.com/snakevash/p/2034336.html