在类构造函数中设置默认值 C#
我需要一个默认值设置以及许多不同的页面访问和更新..最初我可以像这样在类构造函数中设置默认值吗?在 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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将其放在声明中:
private static double _hiprofit = 0.09;
或者,如果这是一个更复杂的初始化,您可以在静态构造函数中完成:
首选前者,因为后者会降低性能:http://blogs.msdn.com/b/brada/archive/2004/04/17/115300.aspx
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:
The former is preferred as the latter pays a performance penalty: http://blogs.msdn.com/b/brada/archive/2004/04/17/115300.aspx
不,您必须使用实际的静态构造函数包围对属性的赋值,如下所示:
注意:静态构造函数不能声明为私有/公共,并且不能具有参数。
No, you would have to surround the assignment to the property with an actual static constructor like so:
Note: a static constructor can not be declared private/public and cannot have parameters.
您就快完成了,您只需要使用 构造函数。
You're almost there, you just need to use a constructor.