我知道这个问题已经被问过,但我还没有看到很短的,明确的答案,所以我希望他们不会消除这个问题,现在我会得到一个明确的答案:
I know this question has been asked before, but I have yet to see a short, clear answer, so I'm hoping they won't remove this question and I will now get a clear answer:
我目前工作在C#5.0; .NET 4.5; VS 2012年我主要是一个Delphi的人,虽然我已经用C#做了很多。
I am currently working in C# 5.0; .NET 4.5; VS 2012. I am mostly a Delphi guy although I've done lots with C#.
在德尔福我已经写了数百名使用以下排序设计(大大简化HERE)类工厂:
In Delphi I have written hundreds of class factories that use the following sort of design (MUCH SIMPLIFIED HERE):
unit uFactory;
interface
type
TClassofMyClass = class of TMyClass;
TFactoryDict = TDictionary<TMyEnum, TClassofMyClass>;
var fDict:TFactoryDict;
implementation
procedure initDict;
begin
fDict:=TFactoryDict.create;
fDict.add(myEnum1, TMyClass1);
fDict.add(myEnum2, TMyClass2);
fDict.add(myEnum3, TMyClass3);
end;
function Factory(const aEnum: TMyEnum): TMyClass;
var
ClassofMyClass: TClassofMyClass;
begin
if fDict.TryGetValue(aEnum, ClassofMyClass) then
result := ClassofMyClass.Create(aParam);
end;
end.
现在:做我怎么做这样的事在C#?似乎还有否在C#中类的类型。我失去了一些东西?我怎样才能实现这种类型的类工厂的简单和优雅的C#?这样的设计可以在Python实现以及 - ?!为什么C#是雪上加霜
Now: HOW do I do something like this in C#?! Seems there is NO 'class of ' type in C#. Am I missing something? How can I implement this type of class factory simply and elegantly in C#? This design can be implemented in Python as well - why should C# be worse?!
您可以使用Type:
Dictionary<ClassEnum, Type> TypeDictionary = new Dictionary<ClassEnum, Type>();
public void InitDictionary()
{
TypeDictionary.Add(ClassEnum.FirstClass, typeof(FirstClass));
//etc...
}
public object Factory(ClassEnum type)
{
if (!TypeDictionary.ContainsKey(type))
return null;
var constructor = TypeDictionary[type].GetConstructor(....);
return constructor.Invoke(....);
}
不过,我认为你应该使用泛型方法:
But I think you should use a generic method:
public T Factory<T>(): where T is MyBaseClass
{
var type = typeof(T);
var constructor = type.GetConstructor(....);
return constructor.Invoke(....) as T;
}
下面是各种参数化建设:
Here is a variety for parameterized construction:
public T Factory<T>(params object[] args): where T is MyBaseClass
{
var argList = new List<object>(args);
var type = typeof(T);
var argtypes = argList.Select(o => o.GetType()).ToArray();
var constructor = type.GetConstructor(argtypes);
return constructor.Invoke(args) as T;
}
当然,正如第一个例子,这将抛出一个NullPointerException异常,如果它不能找到匹配的构造......
And of course; As with the first example, this will throw a nullpointerexception if it can't find a matching constructor...