简体   繁体   English

在 ASP .NET 中使用静态类初始化另一个静态类的成员

[英]Using a Static Class to Initialize Members of another Static Class in ASP .NET

Is there anyway for a static class to use values set in another static class from a different namespace to initialize some of it's members?无论如何,静态类是否可以使用来自不同命名空间的另一个静态类中设置的值来初始化它的一些成员? Is there anyway to dictate the order they get established in?反正有没有规定他们建立的顺序?

eg例如

namespace Utility
{
    using Config;

    public static class Utility
    {
        public static UtilityObject myUtil = new UtilityObject(ConfigContext.myValue)
    }
}
...
// somewhere in a different file/project
...
namespace Config
{
    public static class ConfigContext
    {
        public static string myValue => ConfigurationManager.AppSettings["key"];
    }
}

This is a simplified example of the basic pattern I'm trying to accomplish;这是我试图完成的基本模式的简化示例; I would like to take values that are in a config file which are loaded into static class ConfigContext , and use them to initialize members of a static class Utility .我想获取加载到static class ConfigContext的配置文件中的值,并使用它们来初始化static class Utility成员。

You can't dictate the order of static initialization.您不能规定静态初始化的顺序。 But you can avoid the problem entirely by deferring initialization using lazy logic.但是您可以通过使用惰性逻辑推迟初始化来完全避免这个问题。

public static class Utility
{
    private static Lazy<UtilityObject> _myUtil = null;

    private static Utility()
    {
        _myUtil = new Lazy<UtilityObject>( () => new UtilityObject(ConfigContext.myValue) );
    }

    public static myUtil => _myUtil.Value;
}

Using this technique, the utility object isn't initialized until it is actually used.使用这种技术,实用程序对象在实际使用之前不会被初始化。

If the logic to initialize ConfigContext has a similar issue, you can use a Lazy there too, and all of your lazy fields will get initialized in a cascading fashion, in the order they are needed.如果初始化ConfigContext的逻辑有类似的问题,您也可以在那里使用 Lazy,并且您的所有惰性字段都将按照需要的顺序以级联方式进行初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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