将DLL放在资源文件中,利用反射来调用它的泛型函数!

public static string ListToJson<T>(T List)
        {
            

            System.Reflection.Assembly ass = System.Reflection.Assembly.Load(SCB.FDS.Client.AutoUpdate.Resource.Newtonsoft_Json);
            Type type = ass.GetType("Newtonsoft.Json.JsonConvert");
            MethodInfo method = GetMethodToString(type, "SerializeObject", 1);

            return method.Invoke(null, new object[] { List }).ToString();   
        }

        public static T JsonToList<T>(string List)
        {
            

            System.Reflection.Assembly ass = System.Reflection.Assembly.Load(SCB.FDS.Client.AutoUpdate.Resource.Newtonsoft_Json);

            Type type = ass.GetType("Newtonsoft.Json.JsonConvert");

            MethodInfo method = GetMethodToT(type, "DeserializeObject", 1).MakeGenericMethod(typeof(T));
            
            T t = (T)method.Invoke(null, new object[] { List });
            
            return t;
        }

        private static MethodInfo GetMethodToT(Type type, string methodName, int paramCount)
        {
            return type.GetMethods().FirstOrDefault(m => { return m.ReturnType != typeof(string) && m.ReturnType != typeof(object) && m.Name == methodName && m.GetParameters().Count() == paramCount; });
        }

        private static MethodInfo GetMethodToString(Type type, string methodName, int paramCount)
        {
            return type.GetMethods().FirstOrDefault(m => { return m.ReturnType == typeof(string) && m.Name == methodName && m.GetParameters().Count() == paramCount; });
        }
  

 

posted on 2013-05-08 17:09  米高佐敦  阅读(225)  评论(0编辑  收藏  举报