简体   繁体   中英

Is there an api to bypass the static constructor of a class

Is there a way I can initialize a class which contains a static constructor (that throws an exception), without executing the static constructor?

I've tried these so far:

Activator.CreateInstance(typeof(Foo));

FormatterServices.GetUninitializedObject(typeof(Foo));

var s = new XmlSerializer(typeof(Foo));
Foo f = (Foo)s.Deserialize(new StringReader("<Foo></Foo>"));

Aside from using a CRL Profiler api with something like MS Fakes or TypeMock, can this be done using any API in the baseclass library, or perhaps something unmanaged.

Example class that I want to use.

public class Foo
{
    static Foo()
    {
        throw new Exception("Populate Bar from the database, which isn't available.");
    }

    public int Bar { get; set; }
}

No, not that I'm aware of, at least directly.

Static constructors are there exactly to be automatically called whenever anything happens either to anything (method, property, ...) static from the class, or when you create the very first instance of that class (if it's possible).

This means, basically, that they are kind of always called, whether you like/want it or not. It's always automatic and it always happens.

One option, though, would be to use some nasty reflection to extract working code, replace (or entirely remove) static constructor and rebuild the class from scratch. This might help a bit on this.

Problem is that another great question arises: how to replace that type during its usage. If it comes from an interface, it might be easier, but if it's a concrete type being directly called, you have got yourself a great challenge.

Now, if you take this to a higher abstraction level, this issue might be solved using other approaches, like proxying that request to some other database, or even translating it to another language.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM