From 73345ecccbd794c2952b2dbedd86987a3e0d1393 Mon Sep 17 00:00:00 2001 From: Mike Burns Date: Wed, 2 Mar 2016 15:27:14 +1000 Subject: [PATCH] Added non-generic version of CreateInstance Ability to dynamically call CreateInstance with Type object rather than generic. --- AFrame.Core/Controls/Control.cs | 49 +++++++++++++++++++-------------- 1 file changed, 29 insertions(+), 20 deletions(-) diff --git a/AFrame.Core/Controls/Control.cs b/AFrame.Core/Controls/Control.cs index a3109a3..ef1b251 100644 --- a/AFrame.Core/Controls/Control.cs +++ b/AFrame.Core/Controls/Control.cs @@ -163,34 +163,43 @@ public virtual T CreateControl(IEnumerable searchProperties) return control; } #endregion - - public static T CreateInstance(IContext context, Control parent) where T : Control + + public static Control CreateInstance(Type type, IContext context, Control parent) { //If type has constructor with 1 parameter and is type IContext. Then use that. //Else use default constructor. - - var type = typeof(T); - - //First constructor attempt. - var ctor = type.GetConstructor(new[] { context.GetType() }); - if (ctor != null) + + Control local; + ConstructorInfo constructor = type.GetConstructor(new Type[] { context.GetType() }); + if (constructor != null) + { + local = constructor.Invoke(new object[] { context }) as Control; + if (local == null) + { + throw new Exception("Type is not of type 'Control': " + type.Name); + } + local.Parent = parent; + return local; + } + constructor = type.GetConstructor(Type.EmptyTypes); + if (constructor == null) { - var ctrl = (T)ctor.Invoke(new object[] { context }); - ctrl.Parent = parent; - return ctrl; + throw new Exception("No appropriate constructors found for " + type.Name); } - - //Second constructor attempt. - ctor = type.GetConstructor(Type.EmptyTypes); - if (ctor != null) + local = constructor.Invoke(new object[0]) as Control; + if (local == null) { - var ctrl = (T)ctor.Invoke(new object[] { }); - ctrl.Context = context; - ctrl.Parent = parent; - return ctrl; + throw new Exception("Type is not of type 'Control': " + type.Name); } + local.Context = context; + local.Parent = parent; + return local; + } - throw new Exception("No appropriate constructors found for " + type.Name); + public static T CreateInstance(IContext context, Control parent) where T : Control + { + var type = typeof(T); + return CreateInstance(type, context, parent) as T; } #region Create Controls