兩個選項(使用字符串和數據結構)工作的優良 - 它只是取決於你想要擁有的表達式轉換成字符串傳遞在導線(這可能會導致更小的消息大小)或轉移數據結構直接(線的大小可能會更大,但您將在客戶端和服務器之間共享相同的表達式樹)。
下面的代碼顯示了你有一個例子可能的數據結構 - 樹(這是目前二元但它並沒有成爲)。
public class StackOverflow_6915554
{
[DataContract]
[KnownType(typeof(LeafExpression))]
[KnownType(typeof(BinaryExpression))]
public class Expression
{
}
[DataContract]
public class LeafExpression : Expression
{
[DataMember]
public string Name;
}
[DataContract]
public class BinaryExpression : Expression
{
[DataMember]
public BinaryOperator Operator;
[DataMember]
public Expression Left;
[DataMember]
public Expression Right;
}
public enum BinaryOperator
{
And,
Or,
}
public static void Test()
{
List<Expression> expressions = new List<Expression>();
expressions.Add(new BinaryExpression
{
Left = new BinaryExpression
{
Left = new LeafExpression { Name = "A" },
Operator = BinaryOperator.And,
Right = new LeafExpression { Name = "B" },
},
Operator = BinaryOperator.Or,
Right = new BinaryExpression
{
Left = new LeafExpression { Name = "C" },
Operator = BinaryOperator.And,
Right = new LeafExpression { Name = "D" },
}
});
expressions.Add(new BinaryExpression
{
Left = new LeafExpression { Name = "E" },
Operator = BinaryOperator.Or,
Right = new LeafExpression { Name = "F" }
});
expressions.Add(new LeafExpression { Name = "G" });
XmlWriterSettings ws = new XmlWriterSettings
{
Indent = true,
IndentChars = " ",
Encoding = new UTF8Encoding(false),
OmitXmlDeclaration = true,
};
MemoryStream ms = new MemoryStream();
XmlWriter w = XmlWriter.Create(ms, ws);
DataContractSerializer dcs = new DataContractSerializer(typeof(List<Expression>));
dcs.WriteObject(w, expressions);
w.Flush();
Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
}
}