Setting the default value of a C# Optional Parameter

后端 未结 3 1907
甜味超标
甜味超标 2020-12-01 17:58

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

3条回答
  •  一个人的身影
    2020-12-01 18:39

    One option is to make the default value null and then populate that appropriately:

    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.

    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.

提交回复
热议问题