Featured post
c# - How do I explicitly run the static constructor of an unknown type? -
possible duplicate:
how invoke static constructor reflection?
i've got initialization code in static constructor of various classes. can't create instances, nor know types in advance. ensure classes loaded.
i tried this:
footype.typeinitializer.invoke (new object[0]);
but got memberaccessexception: type initializer not callable.
i'm assuming because cctor private? there way fix without changing architecture?
edit: found workaround using runtimehelpers.runclassconstructor
, way seems barely documented in msdn , i'm not sure if hack or reasonable, prod system way.
i'm not sure why works, far reason (with skeet) if have static class
public static class statics1 { public static string value1 { get; set; } static statics1() { console.writeline("statics1 cctor"); value1 = "initialized 1"; } }
the code:
type statictype = typeof (statics1); statictype.typeinitializer.invoke(null); or statictype.typeinitializer.invoke(new object[0]);
will throw exception, because somehow resolves .ctor, instead of .cctor of class.
if use explicitly static class, treated abstract sealed class, exception abstract class cannot instantiated, , if use regular class static constructor, exception type initializer not callable.
but if use invoke overload 2 parameters (instance, params), this:
type statictype = typeof (statics1); statictype.typeinitializer.invoke(null, null);
explicitly stating invoking static method (that's meaning of first null - no instance == static), works , initializes class.
that said, static constructors strange beasts. invoking 1 in way call static constructor if executed, i.e., code:
console.writeline(statics1.value1); type statictype = typeof (statics1); statictype.typeinitializer.invoke(null, null);
will call static constructor twice. if cctors have potentially important sideeffects, such creating files, opening databases, etc, might want rethink approach.
also, though prefer static constructors reasons of readability, performance perspective, field initializers bit faster static constructors
- Get link
- X
- Other Apps
Comments
Post a Comment