我有以下类定义:
public abstract class BaseExample<T> where T : BaseExample<T>
{
public abstract T Clone(T original);
}
及其遗产
public class Example01 : BaseExample<Example01>
{
public override Example01 Clone(Example01 original)
{
return this; // not the actual implementation
}
}
public class Example02 : BaseExample<Example02>
{
public override Example02 Clone(Example02 original)
{
return this; // not the actual implementation
}
}
如何声明带有类型或基类的变量?由于以下声明无法编译:
private BaseExample<T> declarationA;
private BaseExample<T> declarationA;
private BaseExample declarationB;
它不起作用,因为您分配给泛型类型的任何内容T
都无法真正BaseExample<T>
。
BaseExample<int> declarationA;
在上述情况下int
不能真正BaseExample<int>
(int
!= BaseExample<int>
)
我需要有一个可以同时接收
Example01
或Example02
值的BaseExample
实例。 例如:BaseExample a = new Example01()
你不能 - BaseExample<Example01>
和BaseExample<Example02>
是不同的类型。 没有一个基本类型(除了 object
)可以容纳任何一种类型。
假设您可以:
BaseExample a = new Example01();
a.Clone()
返回的返回类型是什么?
如果您的代码位于泛型类 ot 方法中,那么您可以:
public T MyMethod<T>(T value) where T : BaseExample<T>
{
BaseExample<T> a = value;
return value.Close();
}
但是你必须在调用方法时指定类型,例如
Example01 a1 = new Example01();
Example01 a2 = MyMethod(a1); // MyMethod<Example01> is inferred by the compiler
如前所述,由于Generic<T1>
和Generic<T2>
是不同的类,因此不能将它们分配给同一变量。
我解决这个问题的一种方法是使用非泛型基类,这样
public abstract class BaseExample { ... }
public abstract class BaseExmmple<T> : BaseExample
where T : BaseExample<T>
{ ... }
这可以通过实现internal abstract
成员来变得更加安全,这样外部类就无法实现BaseExample
。
如果您希望能够从非泛型类型的变量中保存的对象调用.Clone()
,则应实现一个由泛型类包装的 object
返回表单以调用泛型表单。