代码改变世界

C#类型转换1

2012-09-15 16:52  hongjiumu  阅读(446)  评论(0编辑  收藏  举报
namespace WDBuyNET.DMSFrame.Utils.Helpers
{
    public static class ReflectionHelper
    {
        public class TypeLoadConfig
        {
            private bool copyToMemory;
            private bool loadAbstractType;
            private string targetFilePostfix;
            public bool CopyToMemory
            {
                get
                {
                    return this.copyToMemory;
                }
                set
                {
                    this.copyToMemory = value;
                }
            }
            public bool LoadAbstractType
            {
                get
                {
                    return this.loadAbstractType;
                }
                set
                {
                    this.loadAbstractType = value;
                }
            }
            public string TargetFilePostfix
            {
                get
                {
                    return this.targetFilePostfix;
                }
                set
                {
                    this.targetFilePostfix = value;
                }
            }
            public TypeLoadConfig()
            {
                this.copyToMemory = false;
                this.loadAbstractType = false;
                this.targetFilePostfix = ".dll";
            }
            public TypeLoadConfig(bool copyToMem, bool loadAbstract, string postfix)
            {
                this.copyToMemory = false;
                this.loadAbstractType = false;
                this.targetFilePostfix = ".dll";
                this.copyToMemory = copyToMem;
                this.loadAbstractType = loadAbstract;
                this.targetFilePostfix = postfix;
            }
        }
        public static void CopyProperty(object source, object target)
        {
            ReflectionHelper.CopyProperty(source, target, null);
        }
        public static void CopyProperty(object source, object target, IList<MapItem> propertyMapItemList)
        {
            Type type = source.GetType();
            Type type2 = target.GetType();
            PropertyInfo[] properties = type.GetProperties();
            if (propertyMapItemList != null)
            {
                foreach (MapItem current in propertyMapItemList)
                {
                    object property = ReflectionHelper.GetProperty(source, current.Source);
                    ReflectionHelper.SetProperty(target, current.Target, property);
                }
            }
            else
            {
                PropertyInfo[] array = properties;
                for (int i = 0; i < array.Length; i++)
                {
                    PropertyInfo propertyInfo = array[i];
                    if (propertyInfo.CanRead)
                    {
                        object property2 = ReflectionHelper.GetProperty(source, propertyInfo.Name);
                        ReflectionHelper.SetProperty(target, propertyInfo.Name, property2);
                    }
                }
            }
        }
        private static void DistillMethods(Type interfaceType, ref IList<MethodInfo> methodList)
        {
            MethodInfo[] methods = interfaceType.GetMethods();
            for (int i = 0; i < methods.Length; i++)
            {
                MethodInfo methodInfo = methods[i];
                bool flag = false;
                foreach (MethodInfo current in methodList)
                {
                    if (current.Name == methodInfo.Name && current.ReturnType == methodInfo.ReturnType)
                    {
                        ParameterInfo[] parameters = current.GetParameters();
                        ParameterInfo[] parameters2 = methodInfo.GetParameters();
                        if (parameters.Length == parameters2.Length)
                        {
                            bool flag2 = true;
                            for (int j = 0; j < parameters.Length; j++)
                            {
                                if (parameters[j].ParameterType != parameters2[j].ParameterType)
                                {
                                    flag2 = false;
                                }
                            }
                            if (flag2)
                            {
                                flag = true;
                                break;
                            }
                        }
                    }
                }
                if (!flag)
                {
                    methodList.Add(methodInfo);
                }
            }
            Type[] interfaces = interfaceType.GetInterfaces();
            i = 0;
            while (i < interfaces.Length)
            {
                Type interfaceType2 = interfaces[i];
                ReflectionHelper.DistillMethods(interfaceType2, ref methodList);
                i++;
            }
        }
        public static IList<MethodInfo> GetAllMethods(params Type[] interfaceTypes)
        {
            for (int i = 0; i < interfaceTypes.Length; i++)
            {
                Type type = interfaceTypes[i];
                if (!type.IsInterface)
                {
                    throw new Exception("Target Type must be interface!");
                }
            }
            IList<MethodInfo> result = new List<MethodInfo>();
            i = 0;
            while (i < interfaceTypes.Length)
            {
                Type interfaceType = interfaceTypes[i];
                ReflectionHelper.DistillMethods(interfaceType, ref result);
                i++;
            }
            return result;
        }
        public static object GetFieldValue(object obj, string fieldName)
        {
            Type type = obj.GetType();
            FieldInfo field = type.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField);
            if (field == null)
            {
                throw new Exception(string.Format("The field named '{0}' not found in '{1}'.", fieldName, type));
            }
            return field.GetValue(obj);
        }
        public static string GetMethodFullName(MethodInfo method)
        {
            return string.Format("{0}.{1}()", method.DeclaringType, method.Name);
        }
        public static object GetProperty(object obj, string propertyName)
        {
            return obj.GetType().InvokeMember(propertyName, BindingFlags.GetProperty, null, obj, null);
        }
        public static Type GetType(string typeAndAssName)
        {
            string[] array = typeAndAssName.Split(new char[]
            {
                ','
            });
            return (array.Length >= 2) ? ReflectionHelper.GetType(array[0].Trim(), array[1].Trim()) : Type.GetType(typeAndAssName);
        }
        public static Type GetType(string typeFullName, string assemblyName)
        {
            Type result;
            if (assemblyName == null)
            {
                result = Type.GetType(typeFullName);
            }
            else
            {
                Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
                Assembly[] array = assemblies;
                for (int i = 0; i < array.Length; i++)
                {
                    Assembly assembly = array[i];
                    if (assembly.FullName.Split(new char[]
                    {
                        ','
                    })[0].Trim() == assemblyName.Trim())
                    {
                        result = assembly.GetType(typeFullName);
                        return result;
                    }
                }
                Assembly assembly2 = Assembly.Load(assemblyName);
                result = ((!(assembly2 != null)) ? null : assembly2.GetType(typeFullName));
            }
            return result;
        }
        public static string GetTypeFullName(Type t)
        {
            return t.FullName + "," + t.Assembly.FullName.Split(new char[]
            {
                ','
            })[0];
        }
        public static IList<TBase> LoadDerivedInstance<TBase>(Assembly asm)
        {
            IList<TBase> list = new List<TBase>();
            Type typeFromHandle = typeof(TBase);
            Type[] types = asm.GetTypes();
            for (int i = 0; i < types.Length; i++)
            {
                Type type = types[i];
                bool arg_41_0;
                if (typeFromHandle.IsAssignableFrom(type) && !type.IsAbstract)
                {
                    arg_41_0 = type.IsInterface;
                }
                else
                {
                    arg_41_0 = true;
                }
                if (!arg_41_0)
                {
                    TBase item = (TBase)Activator.CreateInstance(type);
                    list.Add(item);
                }
            }
            return list;
        }
        public static IList<Type> LoadDerivedType(Type baseType, string directorySearched, bool searchChildFolder, ReflectionHelper.TypeLoadConfig config)
        {
            if (config == null)
            {
                config = new ReflectionHelper.TypeLoadConfig();
            }
            IList<Type> list = new List<Type>();
            IList<Type> result;
            if (searchChildFolder)
            {
                ReflectionHelper.LoadDerivedTypeInAllFolder(baseType, list, directorySearched, config);
                result = list;
            }
            else
            {
                ReflectionHelper.LoadDerivedTypeInOneFolder(baseType, list, directorySearched, config);
                result = list;
            }
            return result;
        }
        private static void LoadDerivedTypeInAllFolder(Type baseType, IList<Type> derivedTypeList, string folderPath, ReflectionHelper.TypeLoadConfig config)
        {
            ReflectionHelper.LoadDerivedTypeInOneFolder(baseType, derivedTypeList, folderPath, config);
            string[] directories = Directory.GetDirectories(folderPath);
            if (directories != null)
            {
                string[] array = directories;
                for (int i = 0; i < array.Length; i++)
                {
                    string folderPath2 = array[i];
                    ReflectionHelper.LoadDerivedTypeInAllFolder(baseType, derivedTypeList, folderPath2, config);
                }
            }
        }
        private static void LoadDerivedTypeInOneFolder(Type baseType, IList<Type> derivedTypeList, string folderPath, ReflectionHelper.TypeLoadConfig config)
        {
            string[] files = Directory.GetFiles(folderPath);
            string[] array = files;
            for (int i = 0; i < array.Length; i++)
            {
                string text = array[i];
                if (config.TargetFilePostfix == null || text.EndsWith(config.TargetFilePostfix))
                {
                    Assembly assembly = null;
                    try
                    {
                        assembly = ((!config.CopyToMemory) ? Assembly.LoadFrom(text) : Assembly.Load(FileHelper.ReadFileReturnBytes(text)));
                    }
                    catch (Exception )
                    {
                    }
                    if (assembly != null)
                    {
                        Type[] types = assembly.GetTypes();
                        Type[] array2 = types;
                        for (int j = 0; j < array2.Length; j++)
                        {
                            Type type = array2[j];
                            bool arg_C5_0;
                            if (type.IsSubclassOf(baseType) || baseType.IsAssignableFrom(type))
                            {
                                arg_C5_0 = (!config.LoadAbstractType && type.IsAbstract);
                            }
                            else
                            {
                                arg_C5_0 = true;
                            }
                            if (!arg_C5_0)
                            {
                                derivedTypeList.Add(type);
                            }
                        }
                    }
                }
            }
        }
        public static MethodInfo SearchGenericMethodInType(Type originType, string methodName, Type[] argTypes)
        {
            MethodInfo[] methods = originType.GetMethods();
            MethodInfo result;
            for (int i = 0; i < methods.Length; i++)
            {
                MethodInfo methodInfo = methods[i];
                if (methodInfo.ContainsGenericParameters && methodInfo.Name == methodName)
                {
                    bool flag = true;
                    ParameterInfo[] parameters = methodInfo.GetParameters();
                    if (parameters.Length == argTypes.Length)
                    {
                        for (int j = 0; j < parameters.Length; j++)
                        {
                            if (!parameters[j].ParameterType.IsGenericParameter)
                            {
                                if (parameters[j].ParameterType.IsGenericType)
                                {
                                    if (parameters[j].ParameterType.GetGenericTypeDefinition() != argTypes[j].GetGenericTypeDefinition())
                                    {
                                        flag = false;
                                        break;
                                    }
                                }
                                else
                                {
                                    if (parameters[j].ParameterType != argTypes[j])
                                    {
                                        flag = false;
                                        break;
                                    }
                                }
                            }
                        }
                        if (flag)
                        {
                            result = methodInfo;
                            return result;
                        }
                    }
                }
            }
            result = null;
            return result;
        }
        public static MethodInfo SearchMethod(Type originType, string methodName, Type[] argTypes)
        {
            MethodInfo method = originType.GetMethod(methodName, argTypes);
            MethodInfo result;
            if (method != null)
            {
                result = method;
            }
            else
            {
                MethodInfo methodInfo = ReflectionHelper.SearchGenericMethodInType(originType, methodName, argTypes);
                if (methodInfo != null)
                {
                    result = methodInfo;
                }
                else
                {
                    Type baseType = originType.BaseType;
                    if (baseType != null)
                    {
                        while (baseType != typeof(object))
                        {
                            MethodInfo method2 = baseType.GetMethod(methodName, argTypes);
                            if (method2 != null)
                            {
                                result = method2;
                                return result;
                            }
                            MethodInfo methodInfo2 = ReflectionHelper.SearchGenericMethodInType(baseType, methodName, argTypes);
                            if (methodInfo2 != null)
                            {
                                result = methodInfo2;
                                return result;
                            }
                            baseType = baseType.BaseType;
                        }
                    }
                    if (originType.GetInterfaces() != null)
                    {
                        IList<MethodInfo> allMethods = ReflectionHelper.GetAllMethods(originType.GetInterfaces());
                        foreach (MethodInfo current in allMethods)
                        {
                            if (!(current.Name != methodName))
                            {
                                ParameterInfo[] parameters = current.GetParameters();
                                if (parameters.Length == argTypes.Length)
                                {
                                    bool flag = true;
                                    for (int i = 0; i < parameters.Length; i++)
                                    {
                                        if (parameters[i].ParameterType != argTypes[i])
                                        {
                                            flag = false;
                                            break;
                                        }
                                    }
                                    if (flag)
                                    {
                                        result = current;
                                        return result;
                                    }
                                }
                            }
                        }
                    }
                    result = null;
                }
            }
            return result;
        }
        public static void SetFieldValue(object obj, string fieldName, object val)
        {
            Type type = obj.GetType();
            FieldInfo field = type.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.SetField);
            if (field == null)
            {
                throw new Exception(string.Format("The field named '{0}' not found in '{1}'.", fieldName, type));
            }
            field.SetValue(obj, val);
        }
        public static void SetProperty(IList<object> objs, string propertyName, object proValue)
        {
            object[] array = new object[]
            {
                proValue
            };
            foreach (object current in objs)
            {
                ReflectionHelper.SetProperty(current, propertyName, proValue);
            }
        }
        public static void SetProperty(object obj, string propertyName, object proValue)
        {
            ReflectionHelper.SetProperty(obj, propertyName, proValue, true);
        }
        public static void SetProperty(object obj, string propertyName, object proValue, bool ignoreError)
        {
            Type type = obj.GetType();
            PropertyInfo property = type.GetProperty(propertyName);
            if (!(property != null) || !property.CanWrite)
            {
                if (!ignoreError)
                {
                    throw new Exception(string.Format("The setter of property named '{0}' not found in '{1}'.", propertyName, type));
                }
            }
            else
            {
                try
                {
                    proValue = TypeHelper.ChangeType(property.PropertyType, proValue);
                }
                catch (object )
                {
                }
                object[] args = new object[]
                {
                    proValue
                };
                type.InvokeMember(propertyName, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty, null, obj, args);
            }
        }
        public static object DllInvoke(string DllFileName, string NameSpace, string ClassName, string MethodName, params object[] ObjArrayParams)
        {
            object result;
            try
            {
                Assembly assembly = Assembly.LoadFrom(DllFileName);
                Type[] types = assembly.GetTypes();
                Type[] array = types;
                for (int i = 0; i < array.Length; i++)
                {
                    Type type = array[i];
                    if (type.Namespace == NameSpace && type.Name == ClassName)
                    {
                        MethodInfo method = type.GetMethod(MethodName);
                        if (method != null)
                        {
                            object obj = Activator.CreateInstance(type);
                            result = method.Invoke(obj, ObjArrayParams);
                            return result;
                        }
                    }
                }
            }
            catch (Exception )
            {
            }
            result = 0;
            return result;
        }
    }
}