C# not inferring overloaded method via return type

前端 未结 6 1653
我在风中等你
我在风中等你 2021-01-21 05:17

I\'m writing a C# programlet to crawl a directory and give me a listing of files whose date in the last CSV line is less than the current date. Since this is a programlet, I\'m

6条回答
  •  悲&欢浪女
    2021-01-21 05:47

    So I suppose C# does not overload return types?

    No, indeed it doesn't. The return type isn't part of the signature.

    From section 3.6 of the C# 5 specification (emphasis mine):

    The signature of a method consists of the name of the method, the number of type parameters and the type and kind (value, reference, or output) of each of its formal parameters, considered in the order left to right. For these purposes, any type parameter of the method that occurs in the type of a formal parameter is identified not by its name, but by its ordinal position in the type argument list of the method. The signature of a method specifically does not include the return type, the params modifier that may be specified for the right-most parameter, nor the optional type parameter constraints.

    and

    Overloading of methods permits a class, struct, or interface to declare multiple methods with the same name, provided their signatures are unique within that class, struct, or interface.

    And additionally (for completeness):

    Although out and ref parameter modifiers are considered part of a signature, members declared in a single type cannot differ in signature solely by ref and out.

    Aside from anything else, this restriction helps with readability - it can be hard enough to tell which overload is being called sometimes even when they vary by parameters - it would be even worse if methods could be overloaded by return type. In this case it doesn't even make sense for the methods to be overloaded, as they do opposite things. You should only overload a method if all the overloads perform the same basic task.

    As a side note, your methods don't currently follow .NET naming conventions - and you should be using standard formatting/parsing methods instead of rolling your own.

提交回复
热议问题