[英]Generic method with reflection in factory pattern
我已經將工廠發布到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
字符串。
我讀過這篇文章,所以我知道如何使用反射創建泛型方法。 但是實際上我不知道應該在哪里創建它。 在這樣的工廠中:
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;
}
}
第二種方法行不通,您無法從controlName
獲取類型。 我的想法是,如果您已經有一個封閉的枚舉,請使用它。
public class WpfControlFactory
{
public static IWpfControl CreateWpfControl(WpfControl control, string controlName)
{
IWpfControl wpfControl = default(IWpfControl);
Type type = GetControl(control);
if (type != null && type.IsAssignableFrom(typeof(IWpfControl)))
{
wpfControl = (IWpfControl)Activator.CreateInstance(type);
}
if (wpfControl != null)
{
wpfControl.Name = controlName ?? Consts.DefaultEaControlName;
}
return wpfControl;
}
private Type GetControl( WpfControl control )
{
switch ( control )
{
case WpfControl.Foo : return typeof( FooControlType );
...
}
}
}
這樣,您就可以在枚舉值和控件類型之間建立清晰的1-1映射。
另一方面,如果您依賴字符串,則查找類型要困難得多。 類型可以存在於不同的程序集中。 簡短的類型名稱可能還不夠。 並且使用完整的類型名(還包括程序集名稱)來使調用者更加困難(調用者必須知道類型才能獲得其全名)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.