我需要实现这个:
static class MyStaticClass
{
public const TimeSpan theTime = new TimeSpan(13, 0, 0);
public static bool IsTooLate(DateTime dt)
{
return dt.TimeOfDay >= theTime;
}
}
Run Code Online (Sandbox Code Playgroud)
theTime是一个常数(严重:-),就像?在我的情况下,从设置中读取它是没有意义的,例如.而且我希望它能够被初始化一次并且永远不会改变.
但是C#似乎不允许函数(构造函数)初始化常量.怎么克服这个?
ash*_*vey 60
在此之后使用readonly而不是const可以初始化而不是修改.这就是你要找的东西吗?
代码示例:
static class MyStaticClass
{
public static readonly TimeSpan theTime;
static MyStaticClass
{
theTime = new TimeSpan(13, 0, 0)
}
}
Run Code Online (Sandbox Code Playgroud)
Jam*_*unt 37
常量必须是编译时常量,编译器无法在编译时评估构造函数.使用readonly和static构造函数.
static class MyStaticClass
{
static MyStaticClass()
{
theTime = new TimeSpan(13, 0, 0);
}
public static readonly TimeSpan theTime;
public static bool IsTooLate(DateTime dt)
{
return dt.TimeOfDay >= theTime;
}
}
Run Code Online (Sandbox Code Playgroud)
一般来说,我更喜欢在构造函数中初始化而不是直接赋值,因为您可以控制初始化的顺序.
Eti*_*tel 10
C#的const含义与C++的含义不同const.在C#中,const用于基本上为文字定义别名(因此只能用文字初始化).readonly更接近你想要的,但请记住它只影响赋值运算符(除非它的类具有不可变的语义,否则该对象不是真正的常量).
从这个链接:
常量必须是值类型(sbyte,byte,short,ushort,int,uint,long,ulong,char,float,double,decimal或bool),枚举,字符串文字或null引用.
如果要创建对象,则必须执行以下操作static readonly:
static class MyStaticClass
{
public static readonly TimeSpan theTime = new TimeSpan(13, 0, 0);
public static bool IsTooLate(DateTime dt)
{
return dt.TimeOfDay >= theTime;
}
}
Run Code Online (Sandbox Code Playgroud)
public static readonly TimeSpan theTime = new TimeSpan(13, 0, 0);
Run Code Online (Sandbox Code Playgroud)