简体   繁体   English

设置C#可选参数的默认值

[英]Setting the default value of a C# Optional Parameter

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. 'message'的默认参数值必须是编译时常量。

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. 在此, ValidationMessages是一个资源文件。

One option is to make the default value null and then populate that appropriately: 一种选择是将默认值设为null ,然后适当填充:

public void ValidationError(string fieldName, string message = null)
{
    string realMessage = message ?? ValidationMessages.ContactNotFound;
    ...
}

Of course, this only works if you don't want to allow null as a genuine value. 当然,这仅在您不希望将null作为真值时才有效。

Another potential option would be to have a pre-build step which created a file full of const strings based on the resources; 另一个可能的选择是进行预构建步骤,根据资源创建一个充满const字符串的文件; you could then reference those consts. 然后你可以引用那些争论。 It would be fairly awkward though. 但这会很尴尬。

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. 您需要做的是将默认值设置为null,然后在参数在方法体中具有默认值时执行资源查找。

Another option is to split your method into two, and have the one overload call the other, like so: 另一个选择是将您的方法分成两个,并让一个重载调用另一个,如下所示:

public void ValidationError(string fieldName)
{ 
    ValidationError(fieldName, ValidationMessages.ContactNotFound);
}

public void ValidationError(string fieldName, string message)
{
    ...
}

This way also enables you to pass null as a value for message in case that is also a valid value for that parameter. 这种方式还允许您将null作为message的值message ,以防它也是该参数的有效值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM