using System; namespace UniJSON { struct GenericCast { public static T Null() { if (typeof(T).IsClass) { return default(T); } else { throw new MsgPackTypeException("can not null"); } } delegate T CastFunc(S value); static CastFunc s_cast; delegate Func ConstFuncCreator(S value); static ConstFuncCreator s_const; public static Func Const(S value) { if (s_const == null) { s_const = new ConstFuncCreator(GenericCast.CreateConst()); } return s_const(value); } public static T Cast(S value) { if (s_cast == null) { s_cast = new CastFunc(GenericCast.CreateCast()); } return s_cast(value); } } static partial class GenericCast { public static Func CreateCast() { var mi = ConcreteCast.GetMethod(typeof(S), typeof(T)); if (mi == null) { return (Func)((S s) => { return (T)(object)s; }); } else { return (Func)((S s) => { return (T)mi.Invoke(null, new object[] { s }); }); } } public static Func> CreateConst() { var cast = CreateCast(); return (Func>)((S s) => { return (Func)(() => cast(s)); }); } } }