加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#不通过返回类型推断重载方法

发布时间:2020-12-16 00:24:26 所属栏目:百科 来源:网络整理
导读:我正在编写一个C#程序集来抓取目录并给我一个文件列表,其中最后一行CSV行中的日期小于当前日期.由于这是一个程序员,我实际上并没有花太多时间使代码非常干净或任何东西 – 但我认为这完全是一个意见问题. 好奇的是以下一组代码片段.三个静态方法都在同一个类
我正在编写一个C#程序集来抓取目录并给我一个文件列表,其中最后一行CSV行中的日期小于当前日期.由于这是一个程序员,我实际上并没有花太多时间使代码非常干净或任何东西 – 但我认为这完全是一个意见问题.

好奇的是以下一组代码片段.三个静态方法都在同一个类中.

?

public static DateTime dateStringConverter(string mmddyyyy,char delim='/')
    {
            string[] date = mmddyyyy.Split(delim);
            DateTime fileTime = new DateTime(Convert.ToInt32(date[2]),Convert.ToInt32(date[0]),Convert.ToInt32(date[1]));
            return fileTime;
    }

        public static string dateStringGetter()
        {
            string sYear = DateTime.Now.Year.ToString();
            string sMonth = DateTime.Now.Month.ToString().PadLeft(2,'0');
            string sDay = DateTime.Now.Day.ToString().PadLeft(2,'0');
            return sMonth + '/' + sDay + '/' + sYear;
        }

        public static DateTime dateStringGetter()
        {
            string datestring = dateStringGetter();
            return dateStringConverter(datestring);
        }

?

错误消息说:

Error   1   Type 'Poller.Program' already defines a member called 
'dateStringGetter' with the same parameter types

问题方法是dateStringGetter()的第二个重载副本,它当然具有与第二个版本(无)相同的参数类型,但有两个完全不同的返回类型.一个是DateTime,另一个是字符串.具有DateTime返回类型的版本(在编码错误的字符串中)使用字符串类型调用dateStringGetter()的版本.

这不是很好奇吗?那个C#不会单独根据返回类型重载方法吗?我想我已经完成了库的重载,它会根据调用自动检测我想要的返回类型 – 但我不确定.对此我感觉不对劲.

所以我认为C#不会超载返回类型?

解决方法

So I suppose C# does not overload return types?

不,确实没有.返回类型不是签名的一部分.

从C#5规范的第3.6节(强调我的):

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.

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,or interface.

另外(为了完整性):

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.

除了其他任何东西之外,这种限制有助于提高可读性 – 即使它们因参数而异,也很难分辨出哪些重载被调用 – 如果方法可能被返回类型重载,那就更糟了.在这种情况下,对于重载方法甚至没有意义,因为它们做了相反的事情.如果所有重载执行相同的基本任务,则只应重载方法.

作为旁注,您的方法当前不遵循.NET命名约定 – 您应该使用标准格式化/解析方法而不是滚动自己的方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读