代码:
class Base<T,U> where T:Base<T,U>,new() where U :class
{
protected static U _val = null;
internal static void ShowValue()
{
if(_val == null)new T(); //Without this line, it won't work as expected
Console.WriteLine (_val);
}
internal static void Virtual()
{
Console.WriteLine ("Base");
}
}
class Deriv :Base<Deriv,string>
{
static Deriv()
{
_val = "some string value";
}
internal static new void Virtual ()
{
Console.WriteLine ("Deriv");
}
}
public static void Main (string[] args)
{
Deriv.ShowValue();
Deriv.Virtual();
}
多亏了 .NET 的泛型,我可以使用泛型基类中定义的泛型静态方法创建一堆特定的类。它可以在一定程度上模仿继承多态性。但是为了初始化不同版本的静态字段,我必须使用静态构造函数。不幸的是,我们不能直接调用它们,因此,我们必须想办法触发它的调用。上面给出的示例显示了一种方法。但我不喜欢实例化或反射方法。我们也不能对泛型参数的静态方法进行约束。所以,我想问一下,是否还有其他方法可以完成这种工作!
预先感谢!
~~~~~~~~~~~~~~~~
一些结论(可能有点早):
似乎没有解决方法来处理这种情况。我必须实例化一个子类或使用反射。考虑到 .cctors 只需要调用一次,我赞成反射方法,因为在某些情况下, new() 约束不是一种选择——就像你不应该将无参数 ctor 暴露给用户一样。
经过进一步的实验,我发现 .cctors 可能会被多次调用,但只有第一次调用会影响静态字段的设置。这很奇怪,但很奇怪!
class MyClass
{
static int _val = 0;
static MyClass()
{
_val++;
Console.WriteLine (_val);
}
}
public static void Main (string[] args)
{
ConstructorInfo ci = typeof(MyClass).TypeInitializer;
ci.Invoke(new object[0]);
ci.Invoke(new object[0]);
ci.Invoke(new object[0]);
}
//result:
//1
//1
//1
//1