本文介绍了如何声明一个类的实例在C#中的常数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要实现这样的:
static class MyStaticClass
{
public const TimeSpan theTime = new TimeSpan(13, 0, 0);
public static bool IsTooLate(DateTime dt)
{
return dt.TimeOfDay >= theTime;
}
}
theTime是一个常数(严重:-),像π是,在我的情况下,它会是毫无意义的,从设置读它,例如)。我想它进行一次初始化,并且永远不会改变。但是,C#似乎并没有让一个常量由函数(其中一个构造函数)来初始化。如何克服呢?
theTime is a constant (seriously :-), like π is, in my case it'd be pointless to read it from settings, for example). And I'd like it to be initialized once and never change. But C# doesn't seem to allow a constant to be initialized by a function (which a constructor is). How to overcome this?
推荐答案
使用只读
而不是常量
可以初始化,之后不能修改。这就是你要找的是什么?
Using readonly
instead of const
can be initialized and not modified after that. Is that what you're looking for?
这篇关于如何声明一个类的实例在C#中的常数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!