Beispiel #1
0
        public static T CreateInstanct <T>(Def def, params object[] args)
        {
            if (def == null)
            {
                throw new ArgumentNullException(nameof(def));
            }
            //try
            //{
            if (def.InstClassName == null)
            {
                throw new Exception("InstClassName is not defined");
            }

            var type = Type.GetType(def.InstClassName);

            if (type == null)
            {
                throw new Exception($"No type found for with name '{def.InstClassName}'");
            }

            if (!type.IsSubclassOf(typeof(Inst)))
            {
                throw new Exception($"Stated type name '{def.InstClassName}' does not inherent from type Init.");
            }


            var constructors = type.GetConstructors().ToList();

            if (!(constructors?.Any() ?? false))
            {
                throw new Exception($"Failed to find constructor for class '{def.InstClassName}'.");
            }

            if (constructors.Count() > 1)
            {
                throw new Exception($"InstClass '{def.InstClassName}' has more than one constructor. All Instance classes must have only one contructor.");
            }

            var constructor           = constructors.First();
            var constructorParameters = constructor.GetParameters();
            var tempParms             = args.Prepend(def).ToArray();

            if (constructorParameters.Count() != tempParms.Count())
            {
                throw new Exception($"Constructor arguments for class '{def.InstClassName}' does not match the arguments provided. Arguments must be provided to CreateInstance<T> in the same order as the constuctor.");
            }

            for (int n = 0; n < constructorParameters.Count(); n++)
            {
                var parm         = constructorParameters[n];
                var conParmType  = parm.ParameterType;
                var tempParmType = tempParms[n].GetType();

                if (!conParmType.IsAssignableFrom(tempParmType))
                {
                    throw new Exception($"Constructor arguments for class '{def.InstClassName}' does not match the arguments provided. '{conParmType.Name}' is not assignable from '{tempParmType.Name}'. Arguments must be provided to CreateInstance<T> in the same order as the constuctor.");
                }
            }

            var inst = (T)Activator.CreateInstance(type, args: tempParms);

            return(inst);
            //}
            //catch(Exception e)
            //{
            //    throw new Exception($"Failed to create instance of def named '{def.DefName}'", e);
            //}
        }
Beispiel #2
0
 public Inst(Def def)
 {
     _def = def ?? throw new ArgumentNullException(nameof(def));
     _id  = Guid.NewGuid().ToString();
 }