用途:将委托序列化成二进制,一般用于远程调用方法;
示例:
1、单元测试:
[TestMethod]
public void TestSerializableDelegate()
{
MyAction<string> s = list =>
{
Debug.WriteLine(list);
};
s("调用原委托");
string xmls = s.SerializeBinary<MyAction<string>>();
MyAction<string> act = xmls.SerializeDeBinary<MyAction<string>>();
act("反序列化委托调用");
}
2、定义可序列化的委托:
[Serializable]
public delegate void MyAction<in T>(T obj);
/3、二进制序列化扩展方法:
public static class BinarySerializeEx
{
/// <summary> 序列化二进制 支持序列化委托 </summary>
public static string SerializeBinary<T>(this object target)
{
T result = (T)target;
// 序列化
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter format = new BinaryFormatter();
format.Serialize(stream, result);
return Convert.ToBase64String(stream.ToArray());
//return Encoding.UTF8.GetString(stream.ToArray());
}
}
/// <summary> 返序列化二进制 支持反学列话委托 </summary>
public static T SerializeDeBinary<T>(this string target)
{
//using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(target)))
using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(target)))
{
BinaryFormatter format = new BinaryFormatter();
return (T)format.Deserialize(ms);
}
}
}