我正在尝试在下面执行此操作,是否有办法执行此操作,或者 web.configs 是否仅在运行时可用,因为我收到一条红线错误,指出必须是编译时间常数?
应用设置:
<add key="MyString" value="TheValueOfTheString"/>
代码:
public const string MyString = ConfigurationManager.AppSettings["MyString"];
最佳答案
问题是常量的使用。 const 表示该值在设计时是硬编码的。
const string MyString = "the text...";
appsettings 值直到运行时才为人所知,因此它不是一个常量值。相反,您可以使用静态只读值
static readonly MyString = ConfigurationManager.AppSettings["MyString"];
不同之处在于在编译时如何解释值。当使用常量时,引用的是实际值,而不是变量 MyString
。 static readonly
值被编译为变量。
关于c# - web.config 键值对可以用作 asp.net c# 中的编译时间常量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13608354/