set default value in class constructor C#

戏子无情 提交于 2019-12-07 06:10:51

问题


I need a default value set and many different pages access and update..initially can I set the default value in the class constructor like this? What is the proper way to do this in 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;

}

回答1:


You can put it in the declaration: private static double _hiprofit = 0.09; Or if it's a more complicated initialization you can do it in the static constructor:

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

The former is preferred as the latter pays a performance penalty: http://blogs.msdn.com/b/brada/archive/2004/04/17/115300.aspx




回答2:


No, you would have to surround the assignment to the property with an actual static constructor like so:

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

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

Note: a static constructor can not be declared private/public and cannot have parameters.




回答3:


You're almost there, you just need to use a constructor.

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;
    }
}


来源:https://stackoverflow.com/questions/5251621/set-default-value-in-class-constructor-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!