定义两个具有相同参数类型的方法 [英] Define two methods with same parameter type

查看:227
本文介绍了定义两个具有相同参数类型的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我遇到了一个场景,我必须创建一个与现有的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

推荐答案

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

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.

这篇关于定义两个具有相同参数类型的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆