设置 C# 可选参数的默认值
每当我尝试将可选参数的默认值设置为资源文件中的某些内容时,我都会收到以下编译时错误:
“message”的默认参数值必须是编译时常量。
有什么方法可以改变资源文件的工作方式来实现这一点吗?
public void ValidationError(string fieldName,
string message = ValidationMessages.ContactNotFound)
其中,ValidationMessages
是一个资源文件。
Whenever I attempt to set the default value of an optional parameter to something in a resource file, I get a compile-time error of:
Default parameter value for 'message' must be a compile-time constant.
Is there any way that I can change how the resource files work to make this possible?
public void ValidationError(string fieldName,
string message = ValidationMessages.ContactNotFound)
In this, ValidationMessages
is a resource file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一种选择是设置默认值
null
,然后适当地填充该值:当然,只有当您不想允许
null
作为真实值时,这才有效。另一个可能的选择是进行预构建步骤,根据资源创建一个充满 const 字符串的文件;然后你可以引用这些常量。但这会相当尴尬。
One option is to make the default value
null
and then populate that appropriately:Of course, this only works if you don't want to allow
null
as a genuine value.Another potential option would be to have a pre-build step which created a file full of
const
strings based on the resources; you could then reference those consts. It would be fairly awkward though.另一种选择是将您的方法分成两个,并让一个重载调用另一个,如下所示:
这种方式还允许您将
null
作为message
的值传递这种情况也是该参数的有效值。Another option is to split your method into two, and have the one overload call the other, like so:
This way also enables you to pass
null
as a value formessage
in case that is also a valid value for that parameter.不,您将无法使资源直接在默认情况下工作。您需要做的是将默认值设置为 null 之类的值,然后当参数在方法主体中具有默认值时进行资源查找。
No, you will not be able to make the resource work directly in the default. What you need to do is set the default value to something like null and then do the resource lookup when the parameter has the default value in the body of the method.