Пример #1
0
        public static object CreateInstance <T>(this Assembly assembly, Type containerType = null)
        {
            if (assembly == null)
            {
                throw new ArgumentNullException(nameof(assembly));
            }

            string typeName = TypeMixins.GetTypeName(typeof(T), containerType);
            Type   type     = assembly.GetType(typeName);

            if (type == null)
            {
                throw new AssemblyCreateInstanceException($"Could not find '{typeName}' in '{assembly.FullName}'");
            }

            foreach (ConstructorInfo ctor in type.GetConstructors().OrderBy(c => c.GetParameters().Length))
            {
                var parameters = ctor.GetParameters();
                if (parameters.All(pi => pi.HasDefaultValue))
                {
                    return(ctor.Invoke(parameters.Select(x => x.DefaultValue).ToArray()));
                }
            }
            throw new AssemblyCreateInstanceException($"Could not find valid constructor for '{typeof(T).FullName}'");
        }
Пример #2
0
        public static object GetStaticProperty <TContainingType>(this Assembly assembly, string propertyName, Type containerType = null) where TContainingType : class
        {
            if (assembly == null)
            {
                throw new ArgumentNullException(nameof(assembly));
            }
            if (propertyName == null)
            {
                throw new ArgumentNullException(nameof(propertyName));
            }

            string typeName = TypeMixins.GetTypeName(typeof(TContainingType), containerType);
            Type   type     = assembly.GetType(typeName);

            if (type == null)
            {
                throw new AssemblyGetPropertyException($"Could not find '{typeof(TContainingType).FullName}' in '{assembly.FullName}'");
            }

            PropertyInfo property = type.GetProperty(propertyName);

            if (property == null)
            {
                throw new AssemblyGetPropertyException($"Could not find property '{propertyName}' on type '{type.FullName}'");
            }

            if (property.GetMethod == null)
            {
                throw new AssemblyGetPropertyException($"Property '{type.FullName}.{propertyName}' does not have a getter");
            }

            if (!property.GetMethod.IsStatic)
            {
                throw new AssemblyGetPropertyException($"Property '{type.FullName}.{propertyName}' is not static");
            }

            return(property.GetValue(null));
        }