在类构造函数C#中设置默认值 [英] set default value in class constructor C#

查看:152
本文介绍了在类构造函数C#中设置默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;

}


推荐答案

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

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

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

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

这篇关于在类构造函数C#中设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆