문제

I want to understand the efficiency of static classes as I think my basic thinking in this area might be flawed. I often write code like the following with the assumption that the expensive reflection call will happen less frequently since the private variable will hold the information for the accessor. I'm pretty sure that this is good practice in non-static classes and instance properties but is there any benefit in using this construct in static classes or will the private field need to be instantiated on every call to the public accessor?

using System.Reflection;
public static class ApplicationInformation
{
    public static Assembly ExecutingAssembly
    {
        get { return executingAssembly ?? (executingAssembly = Assembly.GetExecutingAssembly()); }
    }
    private static Assembly executingAssembly;
}
도움이 되었습니까?

해결책

Why would it be instantiated on every call? It's a static field, it will "live" for as long as the AppDomain does, just like any other static field.

Admittedly I'd use typeof(ApplicationInformation).Assembly instead, which is probably cheaper... but that's a different matter.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top