您的位置:首页 > 编程语言 > C#

利用C#特性优化AMF反序列化类

2015-06-09 12:18 190 查看
public delegate T AmfReadType<out T>(AMF0Reader instance,bool withType = false);

private static readonly Dictionary<byte, Delegate> ReadMap = new Dictionary<byte, Delegate>();

static AMF0Reader()
{
var type = typeof(AMF0Reader);
var amfReadTypeOf = typeof(AmfReadType<>);
foreach (var method in type.GetMethods())
{
var attribute = method.GetCustomAttribute<AmfReadTypeAttribute>();
if (attribute == null) continue;
ReadMap[attribute.Type] = Delegate.CreateDelegate(amfReadTypeOf.MakeGenericType(method.ReturnType), method);
}
}


泛型委托定义,为了能绑定所有需要反序列化的方法,需要用到C#的一些特性,比如动态创建泛型类型,方法绑定到委托,特性反射等等

调用时
public T Read<T>() => ((AmfReadType<T>)ReadMap[ReadByte()])(this);


C#6.0的单行方法定义,代码更优雅
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c# 泛型 AMF