分配给X的表达式必须是常量吗?

B. *_*non 1 c# string const

我用这段代码得到了这个错误:

const string body = HighPoint; // HighPoint is a string arg passed in to the method
Run Code Online (Sandbox Code Playgroud)

...并且能够通过删除常量来解决它:

string body = HighPoint; 
Run Code Online (Sandbox Code Playgroud)

......或者,当然,分配一个恒定的值:

const string body = "My Dinner with Andre";
Run Code Online (Sandbox Code Playgroud)

......但"我的方式不是一种非常运动的方式"?(无偿的公主新娘参考)

das*_*ght 6

constC#中的关键字表示编译时常量.它与C++和C不同,其中相同的关键字仅需要运行时常量.


Jas*_*rke 5

const在 C# 中与const在 C++ 中不同。

在 C++ 中,const运行时常量。以下操作在 C++ 中有效

IE

const char *CONST_INFO = "hello world";
CONST_INFO = "goodbye world"; //aok
const int i = SomeMethod(); //aok
Run Code Online (Sandbox Code Playgroud)

另一方面,C# 更严格。常量值在编译时必须是常量;没有方法返回或静态类成员。

如果您需要使用一次性值作为常量(即数组或方法返回),您可以使用 static 和 readonly 修饰符来模拟const关键字为您提供的大部分限制:

public static readonly string body = HighPoint;
Run Code Online (Sandbox Code Playgroud)

应该可以正常编译,并且您仍然会像修改值一样遇到类似的限制 const