• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

定义两个具有相同参数类型的方法

用户头像
it1352
帮助1

问题说明

今天我遇到了一个场景,我必须创建一个与现有的c name, params count and params types共享同一方法的方法,如下所示:

Today I ran into a scenario where I have to create a method that share the same name, params count and params types with existent one, Something like this:

public static Department GetDepartment(string departmentName)
{
  //LOGIC
}

public static Department GetDepartment(string employeeID)
{
  //LOGIC
}

乍一看,我只是说了为什么不给它起一个不同的名字来完成工作,但是我做不到!我确实想保持我正在处理的代码的可读性,我希望它成为第一个overloaded
所以我说了为什么不从编译器的角度来看只是为了解决此问题而添加一个假参数.

at first glance I just said why not to name it with a different name and get things done, but I couldn't! I do want to maintain the readability of my code i'm working on, I want it to be overloaded to the first one,
so I said why not to add a fake parameter just to workaround this issue from the compiler Point of view.

 public static Department GetDepartment(string employeeID, object fakePassWtEver)
    {
      //LOGIC
    }

此案例的最佳做法是什么?我看到所有可以让我的代码运行的方法,但是没有一个让我满意的

What is the best practice for this case? I see all the ways can let my code run, but none of them satisfied me

正确答案

#1

保持可读性正是为什么,您应将其重命名:

Maintaining readability is precisely why you should rename it:

Department GetDepartmentByName(...)

Department GetDepartmentByEmployeeID(...)

现在,每当调用该方法时,这是绝对显而易见的.如果您重载该方法,则不是.

Now whenever you call the method, it's absolutely obvious which one you mean. That's very much not the case if you overload the method instead.

随着时间的推移,我变得越来越不愿意过载-有很多一些细微的问题,而且可读性强很多时候会倒下.

I've become increasingly reluctant to overload over time - there are quite a few subtle issues, and readability very often goes down.

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfefic
系列文章
更多 icon
同类精品
更多 icon
继续加载