简体   繁体   中英

C# Methods differ only by optional parameters

I have found this topic, but it's VB...and they get an error: vb issue

Here are my method signatures. Notice one has a different return type.

public static bool PopulateRunWithSimpleValueByFieldIdSync(string fieldValue, string fieldId, IViewModel myself, int index)

VS

public static void PopulateRunWithSimpleValueByFieldIdSync(string fieldValue, string fieldId, IViewModel myself, int index = 0, PopulateDoneCallback populateDone = null)

The actual call I was making:

PopulateRunWithSimpleValueByFieldIdSync(date, dtx.DateField, saver, index);

The compiler decided to pick the first method, and not give me an error. Once the first method was removed (it was unused code), it started calling the second method.

Is there an option somewhere to treat this as an error?

如果您希望在编译时进行标记,则需要使用某种形式的第三方代码分析,因为C#语言规范将当前行为定义为应该发生的事情。

This is per design, according to the specs

Use of named and optional arguments affects overload resolution in the following ways:

  • A method, indexer, or constructor is a candidate for execution if each of its parameters either is optional or corresponds, by name or by position, to a single argument in the calling statement, and that argument can be converted to the type of the parameter.

  • If more than one candidate is found, overload resolution rules for preferred conversions are applied to the arguments that are explicitly specified. Omitted arguments for optional parameters are ignored.

  • If two candidates are judged to be equally good, preference goes to a candidate that does not have optional parameters for which arguments were omitted in the call. This is a consequence of a general preference in overload resolution for candidates that have fewer parameters.

So, no - you can't.

According to the C# language guide ( emphasis mine),

Use of named and optional arguments affects overload resolution in the following ways:

...

If two candidates are judged to be equally good, preference goes to a candidate that does not have optional parameters for which arguments were omitted in the call . This is a consequence of a general preference in overload resolution for candidates that have fewer parameters.

You can use a third party analysis tool to flag this as an error or to use Visual Studio's built in static code analysis too with a custom rule that you implement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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