鉴于这种:
class D{}
class A<T>{}
class B<T> : A<T> {}
class C : B<D> {}
enum openT
{
level1, level2
}
我认为您可能正在寻找这个:
public A<T> FactoryMethod<T>(openT i)
{
if(i == openT.level1)
return new A<T>():
if(i == openT.level2)
return new B<T>():
}
public A<D> FactoryMethod()
{
return new C():
}
public static void Main()
{
A<string> first = OpenFactoryMethod<string>(1);
A<int> second = OpenFactoryMethod<int>(2);
A<D> third = FactoryMethod();
}
请注意, A 不能是抽象的,因为您正在尝试构建它。
不过,我看不到您在这里真正想要完成的工作,因为 C 是一种封闭类型,因此您的工厂方法永远不会对它有意义。
更新
以下可能更接近您正在寻找的内容:
public TAofT FactoryMethod<TAofT, T>() where TAofT : A<T>, new()
{
return new TAofT():
}
public static void Main()
{
A<string> first = FactoryMethod<A<string>, string>();
A<int> second = FactoryMethod<B<int>, int>();
A<D> third = FactoryMethod<C, D>();
}
但是工厂方法似乎是多余的,因为你可以这样做:
public static void Main()
{
A<string> first = new A<string>();
A<int> second = new B<int>();
A<D> third = new C();
}
更新 2
除非你真正想要的是:
public abstract class AEnum<T, T3> where T3 : B<T>, new()
{
private static Func<A<T>> factoryMethod;
public static readonly Level1 = new AEnum<T>(()=>new A<T>());
public static readonly Level2 = new AEnum<T>(()=>new B<T>());
public static readonly Level3 = new AEnum<T>(()=>new T3());
protected AEnum(Func<A<T>> factoryMethod) { this.factoryMethod = factoryMethod; }
public A<T> New() { return this.factoryMethod(); }
}
像这样使用:
public class DEnum : AEnum<D, C>
{
}
和:
public static void Main()
{
A<D> first = DEnum.Level1.New();
A<D> second = DEnum.Level2.New();
A<D> third = DEnum.Level3.New();
}
但是你不能混合枚举类型,因为上面是类型限制为D
.
或者你可以这样做:
public class OpenAEnum<T, T3> : AEnum<T, T3> where T3 : B<T3>
{
}
public class CInt : B<int> {}
public class Cstring : B<string> {}
和:
public static void Main()
{
A<string> first = OpenAEnum<string, CString>.Level1.New();
A<int> second = OpenAEnum<int, CInt>.Level2.New();
A<D> third = OpenAEnum<D, C>.Level3.New();
}
你想做什么?