In the ECMA standard under $14.5.6.2 it states that having a static constructor affects the static field initialization order. I want a way to enforce this, but cannot find a way to check for an explicit static constructor in a type. It seems like the C# runtime automatically generates one if there isn't one already (and if the class has some static fields). Is it possible to check if a class has an explicit static constructor using reflection?
For example - the following will return a constructor in both these cases, and I cannot see any difference between them:
static class NoStaticConstructor
{
public static string Field = "x";
}
static class HasStaticConstructor
{
static HasStaticConstructor() {}
}
public void Test()
{
typeof(NoStaticConstructor)
.GetConstructors(BindingFlags.Static | BindingFlags.NonPublic)
.ShouldBeEmpty(); // FAILS
typeof(HasStaticConstructor)
.GetConstructors(BindingFlags.Static | BindingFlags.NonPublic)
.ShouldNotBeEmpty(); // SUCCEEDS
}
Aucun commentaire:
Enregistrer un commentaire