コード例 #1
0
ファイル: TypeExt.cs プロジェクト: nickeltin1/utils
        public static Type GetGenericInheritor(this Type parentType, Type[] parameterType)
        {
            HashSet <Assembly> assemblies = new HashSet <Assembly> {
                Assembly.GetAssembly(parentType)
            };

            for (int i = 0; i < parameterType.Length; i++)
            {
                if (parameterType[i] != null)
                {
                    assemblies.Add(Assembly.GetAssembly(parameterType[i]));
                }
            }

            List <Type> types = new List <Type>();

            foreach (var assembly in assemblies)
            {
                types.AddRange(assembly.GetTypes());
            }

            foreach (Type type in types)
            {
                if (type.IsClass && !type.IsAbstract && type.BaseType != null && type.BaseType.IsGenericType &&
                    type.BaseType.GetGenericTypeDefinition() == parentType)
                {
                    var hierarchy = TypeExt.GetGenericHierarchy(type.BaseType.ToString());
                    if (hierarchy.Length != parameterType.Length)
                    {
                        continue;
                    }

                    bool parametersMatch = true;
                    for (var i = 0; i < parameterType.Length; i++)
                    {
                        if (parameterType[i] != hierarchy[i])
                        {
                            parametersMatch = false;
                            break;
                        }
                    }

                    if (parametersMatch)
                    {
                        return(type);
                    }
                }
            }

            return(null);
        }
コード例 #2
0
ファイル: TypeExt.cs プロジェクト: nickeltin1/utils
        public static Type[] GetGenericHierarchy(string fullName)
        {
            const char openChar  = '[';
            const char closeChar = ']';

            List <Type> types = new List <Type>();
            var         v     = fullName.Split(new [] { openChar, closeChar }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var s in v)
            {
                types.Add(TypeExt.GetType(s));
            }
            types.RemoveAt(0);
            return(types.Count > 0 ? types.ToArray() : null);
        }