gpt4 book ai didi

c# - 来自设置的常量字符串

转载 作者:行者123 更新时间:2023-11-30 15:29:56 26 4
gpt4 key购买 nike

我想从设置中设置一个常量字符串。

如果我以后想改变程序语言,这很容易;只需修改相应的设置即可!

尝试这个时:

private const string constString =   
"-&" + Properties.Settings.Default.constStringText;

我收到这个错误:

The property or indexer 'Properties.Settings.Default'  
cannot be used in this context because it lacks the get accessor.

有什么想法吗?

最佳答案

由于您打算将其用作可选方法参数的默认值,即:

public void Foo(string something = constString)
{
//do something
}

这个constString必须是一个编译时常量。来自 the MSDN page for "Named and Optional Arguments" :

A default value must be one of the following types of expressions:

  • a constant expression;

  • an expression of the form new ValType(), where ValType is a value type, such as an enum or a struct;

  • an expression of the form default(ValType), where ValType is a value type.

因此,确实没有办法在运行时从配置文件中读取值,然后将其用于可选参数

一种解决方法是将您的 constString 声明为 readonly 字段:

private readonly string constString =   
"-&" + Properties.Settings.Default.constStringText;

然后使您的可选参数成为必需参数,并为不采用该参数的方法创建一个包装重载。该重载依次调用旧方法,并在运行时解析默认值:

public void Foo(string something) //no longer optional
{
//do something
}

public void Foo()
{
Foo(constString); //calls the other overload with the default value
}

关于c# - 来自设置的常量字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22961351/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com