我有多个派生类基类:如何将类<Derived>转换为<Base>类?
class Base { }
class Derived1 : Base { }
class Derived2 : Base { }
然后我有职工类,借此类作为一个通用的类型:
class WorkerClass<T> where T : Base, new()
{
WorkerClass() { }
void DoStuff()
{
T container = new T();
// do stuff
}
}
问题是,当我实例WorkerClass,我只有类型作为变量。我想这样做:
void DoStuff(Type type)
{
WorkerClass<Base> worker_class = null;
if(type == typeof(Derived1))
{
worker_class = new WorkerClass<Derived1>(); // compiler error
}
else if(type == typeof(Derived2))
{
worker_class = new WorkerClass<Derived2>(); // compiler error
}
// lots of common code with worker_class
worker_class.DoStuff();
}
但是,编译器会抱怨隐式铸造WorkerClass<Derived>
到WorkerClass<Base>
。明确的转换也会给出一个错误。编译器建议定义public static implicit operator WorkerClass<T>(WorkerClass<Derived>)
,但我不确定代码的外观。我明显可以把所有的逻辑放在if-else中,但似乎是不必要的重复。
代替'DoStuff(类型类型)'使用通用的方法。 'DoStuff()其中T2:Base,new()' –