开发者

How do I construct local constants from values returned during runtime?

开发者 https://www.devze.com 2023-01-31 23:31 出处:网络
I want \'filename\' to be constant: string filen开发者_JAVA百科ame = \"WR\" + DateTime.Now.ToString(\"M_dd_yyyy\") + \".xls\";

I want 'filename' to be constant:

string filen开发者_JAVA百科ame = "WR" + DateTime.Now.ToString("M_dd_yyyy") + ".xls";

I also want to keep filename as a local and not a field.(I know readonly can solve the problem that way)


You can use a readonly variable. It can be initialized during declaration and changed in the constructor, but nowhere else. And, it only applies to fields, not local variables.

private readonly string filename = "WR" + DateTime.Now.ToString("M_dd_yyyy") + ".xls";

As for why you can't use a const this way - From MSDN:

A constant expression is an expression that can be fully evaluated at compile time.

And, of course DateTime.Now, can't be.

0

精彩评论

暂无评论...
验证码 换一张
取 消