有没有办法在C#中尝试捕获静态属性?

时间:2015-08-17 10:39:42

标签: c#

假设存在代码(服务器端出错):

public class Foo{

    private static readonly Int32 MyProp = 10 / Convert.ToInt32("0");

    public Foo() {
        /// some initialization
    }
}

2 个答案:

答案 0 :(得分:5)

将初始化从字段移动到静态构造函数中:

  public class Foo {
    private static readonly Int32 MyProp;

    public Foo() {
        /// some initialization
    }

    // static constructor for static initialization
    static Foo() {
      try {
        MyProp = 10 / Convert.ToInt32("0");
      }
      catch (SomeException e) {
        ...
      }  
    }
  }

答案 1 :(得分:1)

如果使用静态属性怎么办?

private static int MyProperty
{
    get
    {
        try
        {
            return 10 / Convert.ToInt32("0");
        }
        catch (Exception e)
        {
            return -1;
        }
    }
}