我收到此代码的错误:
const string body = HighPoint; // HighPoint is a string arg passed in to the method
...并且能够通过删除常量来解决它:
string body = HighPoint;
...或者,当然,分配一个常量值:
const string body = "My Dinner with Andre";
...但是“我的方式不是一种非常运动的方式”吗?(无偿公主新娘参考)
C# 中的关键字const表示编译时常量。它与 C++ 和 C 不同,在 C++ 和 C 中,相同的关键字只需要运行时常量。
const在 C# 中与const在 C++ 中不同。
在 C++ 中,const运行时常量。以下操作在 C++ 中有效
IE
const char *CONST_INFO = "hello world";
CONST_INFO = "goodbye world"; //aok
const int i = SomeMethod(); //aok
另一方面,C# 更严格。常量值在编译时必须是常量;没有方法返回或静态类成员。
如果您需要使用一次性值作为常量(即数组或方法返回),您可以使用 static 和 readonly 修饰符来模拟const关键字为您提供的大多数限制:
public static readonly string body = HighPoint;
应该可以正常编译,并且您仍然会像修改值一样遇到类似的限制const