6

我需要一个默认值集和许多不同的页面访问和更新..最初我可以像这样在类构造函数中设置默认值吗?在 C# .NET 中执行此操作的正确方法是什么?

public class ProfitVals
{

    private static double _hiprofit;

    public static Double HiProfit
    {
        get { return _hiprofit; }

        set { _hiprofit = value; }
    }

    // assign default value

    HiProfit = 0.09;

}
4

3 回答 3

9

您可以将其放在声明中:private static double _hiprofit = 0.09; 或者如果它是更复杂的初始化,您可以在静态构造函数中进行:

   private static double _hiprofit; 
   static ProfitVals() 
   {
      _hiprofit = 0.09;
   }

前者是首选,因为后者会付出性能损失:http: //blogs.msdn.com/b/brada/archive/2004/04/17/115300.aspx

于 2011-03-09T20:20:22.560 回答
6

不,您必须使用实际的静态构造函数围绕属性的分配,如下所示:

class ProfitVals
{
    public static double HiProfit { ... }

    static ProfitVals()  // static ctor
    {
       HiProfit = 0.09;
    }
}

注意:静态构造函数不能声明为私有/公共,也不能有参数。

于 2011-03-09T20:17:19.803 回答
1

你快到了,你只需要使用构造函数。

public class ProfitVals {
    private static double _hiprofit;

    public static Double HiProfit
    {
        get { return _hiprofit; }

        set { _hiprofit = value; }
    }

    public ProfitVals() {
        // assign default value
        HiProfit = 0.09;
    }
}
于 2011-03-09T20:17:37.803 回答