如何在初始化静态类之前初始化静态属性?

时间:2013-07-12 20:46:12

标签: c# static

Class2下方有一个需要在调用GetSomething之前设置的属性,但是因为我在Class2顶部访问Class1,所以该属性始终为null它到达Something课程。我似乎无法弄清楚如何更改我的代码以在使用之前设置属性。任何人吗?

修改 我想从form1的构造函数传递依赖项,而不是在链上进一步硬编码。

public partial class form1
{
    private static readonly ISomeConstructedClass someConstructedClass = Class1.SomeConstructedClass;
    public form1()
    {
        someConstructedClass.SomeDependency = new SomeDependency();
        someConstructedClass.Whatever();
    }
}
public static class Class1
{
    public static readonly ISomething something = (ISomething)Class2.GetSomething("something");
    public static ISomeConstructedClass SomeConstructedClass
    {
     get
     {
       return something.SomeConstructedClass;
     }
    }

}         ....     }

public class Class2
{   
    public static ISomeDependency SomeDependency
    {
       get;
       set;
    }
    public static GetSomething(string something)
    {
         switch(something)
         {
            case "something":
               return new Something( SomeDependency );
         }         
    }
}

  public class Something : ISomething
  {
      public ISomeDependency SomeDependency
      {
           get;
           set;
      }
      public Something(ISomeDependency someDependency)
      {
           SomeDependency = someDependency;
      }
  }

2 个答案:

答案 0 :(得分:2)

[回复]编辑:

我对你之前尝试做的事感到困惑,你只需要先创建依赖项。

public partial class form1
{
    private static /*readonly*/ ISomeConstructedClass someConstructedClass;
    public form1()
    {
        Class2.SomeDependency = new SomeDependency();
        someConstructedClass = Class1.SomeConstructedClass;
        someConstructedClass.Whatever();
    }
}

我还会将某些内容创建到属性中,以确保它不会过早初始化(在调用form1构造函数之前)。

public static class Class1
{
    public static ISomething something;
    public static ISomeConstructedClass SomeConstructedClass
    {
        get
        {
            if (something == null) {
                something = (ISomething)Class2.GetSomething("something");
            }
            return something.SomeConstructedClass;
        }
    }
}

您可以使用static constructor。在调用/访问任何静态(或该事件的实例)字段或方法之前调用它。

类似的东西:

static Class2() {
    SomeDependency = SomeDependencyYouNeed;
}

答案 1 :(得分:0)

为什么使用静态方法?看起来你正在尝试一种依赖注入。创建Class2的实例并在构造函数中传递依赖项(并且不使用静态方法),或者将依赖项作为GetSomething()方法的参数传递。

public static GetSomething(string something, ISomeDependency dependency).