我已經發布了我廠codereview.so現在我有這樣的:在工廠模式的反思泛型方法
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;
}
}
但不幸的是,我不能使用CreateWpfControl<TControl>()
因爲我沒有TControl
我已經做只有typeName
字符串。
我讀過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;
}
或者在哪裏?我想我的課是符合SOLID
編輯
下一個可能的版本:
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;
}
}
你能說一下'Enum.TryParse'這行嗎?我無法理解。另外,我不明白爲什麼你堅持重用泛型版本。掌握類型名稱後,可以使用'CreateInstance'的另一個重載,它接受類型名稱作爲字符串。 – 2014-11-01 10:00:32
@WiktorZychla我有支持的控件的枚舉,這很重要,因爲我正在編寫插件到Enterprise Architect,我不支持它提供的所有控件。所以我檢查我的controlType是否支持類型。在第一篇文章中編輯版本。 – 2014-11-01 10:24:57