I've posted my factory to codereview.so now I've got this:
public class WpfControlFactory
{
public static TControl CreateWpfControl<TControl>(string name = null) where TControl : class, IWpfControl
{
TControl wpfControl = default(TControl);
//Avoid some bone-headed exceptions
if (!typeof(TControl).IsAbstract)
{
wpfControl = Activator.CreateInstance<TControl>();
}
if (wpfControl != null)
{
wpfControl.Name = name ?? Consts.DefaultEaControlName;
}
return wpfControl;
}
}
But unfortunately I can't use CreateWpfControl<TControl>()
because I don't have TControl
I've got only typeName
string.
I've read this so I know how to create generic method with reflection. But actually I don't know where should I create it. In factory like this:
public static IWpfControl CreateWpfControl(string controlType, string controlName)
{
Type type = FindType(controlType);
if (type == null)
{
return null;
}
MethodInfo method = typeof(WpfControlFactory).GetMethod("CreateInstance");
MethodInfo generic = method.MakeGenericMethod(type);
return (IWpfControl)generic.Invoke(null, null);
}
private static Type FindType(string typeName)
{
Type type = null;
WpfControl wpfControl;
Enum.TryParse(typeName, out wpfControl);
if (wpfControl != default(WpfControl))
{
type = Type.GetType(typeName);
}
return type;
}
private static TControl CreateInstance<TControl>(string name = null) where TControl : class, IWpfControl
{
TControl wpfControl = default(TControl);
//Avoid some bone-headed exceptions
if (!typeof(TControl).IsAbstract)
{
wpfControl = Activator.CreateInstance<TControl>();
}
if (wpfControl != null)
{
wpfControl.Name = name ?? Consts.DefaultEaControlName;
}
return wpfControl;
}
Or where? I want my class be consistent with SOLID
EDIT
Next possible version:
public class WpfControlFactory
{
public static IWpfControl CreateWpfControl(string controlType, string controlName = null)
{
IWpfControl wpfControl = default(IWpfControl);
Type type = Type.GetType(controlType);
if (type != null && type.IsAssignableFrom(typeof(IWpfControl)))
{
wpfControl = (IWpfControl)Activator.CreateInstance(type);
}
if (wpfControl != null)
{
wpfControl.Name = controlName ?? Consts.DefaultEaControlName;
}
return wpfControl;
}
}