我必须为最终用户提供搜索功能,为此我提供了一个下拉菜单和一个文本框,下拉列表中有EmployeeID,DisplayName,City等选项,在选择下拉值后,他需要在文本框中输入一个值。
如果用户选择EmployeeID,则该值将为Int类型,如果他选择Name或city,则该值将为string类型。
Public Employee getEmpInfo(object querystring, object queryvalue)
{
// code to get the empplyee info
}
我想知道是否有比使用对象类型更好的方法?
您可以像这样重载您的方法:
如果您的参数是int:
public Employee getEmpInfo(int employeeId){
// query by ID
}
或者一个字符串
public Employee getEmpInfo(string employeeName){
// query by name
}
然后,如果你给字符串,第二个将由程序使用,否则第一个将。您可以在文件中编写这些函数。它被称为方法重载。
参考文献:
https://www.geeksforgeeks.org/c-sharp-method-overloading/
https://www.tutorialspoint.com/What-is-method-overloading-in-Chash
另一方面,如果要使用一个函数来搜索所有类型:
public class SearchParams {
public int ID;
public string Name;
public string City;
public SearchParams(int ID = null, string Name = null, string City = null)
{
this.ID = ID;
this.Name = Name;
this.City = City;
}
}
public function getEmpInfo(SearchParams params){
// build query by that parameters
if(ID != null){
// add query by ID
}
}
可以通过为所有属性添加和绑定控件并根据组合框中选定的属性名称在UI中解决此问题,仅显示所选属性的控件。
这种方法可以对某些属性进行非常具体的控制,而不是将所有内容强制为字符串输入。
如何做到这一点取决于UI技术(Web,WinForms,WPF,...)
在我看来,你的方法是错误的。
如果按名称或ID或出生日期搜索Employee,则执行完全不同的操作和SQL操作。
您应该为每种可能性设置一个版本的方法,以便在每个方法中执行一组特定的操作。
如果基于覆盖中的参数类型创建单个方法,则当具有相同类型的不同列时,可能会遇到麻烦。
这是错误的(甚至无法编译):
public Employee GetEmployee(int id)
{
//Instructions..
}
public Employee GetEmployee(string name)
{
//Instructions..
}
public Employee GetEmployee(string city)
{
//Instructions..
}
这将支持所有可能性并保持可读性:
public Employee GetEmployeeByID(int id)
{
//Instructions..
}
public Employee GetEmployeeByName(string name)
{
//Instructions..
}
public Employee GetEmployeeByCity(string city)
{
//Instructions..
}