the code:
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();
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();
}
Thanks to .NET generics, I can create a bunch of specific classes that reuse common static methods defined in the base base class. It can imitate inheritance polymorphism to some extent. But to initialize different versions of static fields, I have to use static constructors. Unfortunately, we cannot call them directly, so we need to figure out a way to call it. The above example showed the way. But I do not like the creation, nor the approach to thinking. We also cannot restrict the static method of the general parameter. So I would like to ask if there is another way to do such a job!
Thanks in advance!
~~~~~~~~~~~~~~~~~
Conclusion (maybe a little early):
, . . , .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]);
}