以前没有缺省参数这个说法时,为了让别人调用我们的代码方便一些,会写很多构造函数,例如一个查询方法贴一些代码如下:
public DataTable Search(
string search)
{
return Search( string.Empty, search, null, null, string.Empty);
}
public DataTable Search( string search, string[] roleIds)
{
return Search( string.Empty, search, roleIds, null, string.Empty);
}
public DataTable Search( string search, string[] roleIds, bool? enabled)
{
return Search( string.Empty, search, roleIds, null, string.Empty);
}
public DataTable Search( string search, string[] roleIds, string auditStates)
{
return Search( string.Empty, search, roleIds, null, auditStates);
}
public DataTable Search( string search, string[] roleIds, bool? enabled, string auditStates)
{
return Search( string.Empty, search, roleIds, enabled, auditStates);
}
{
return Search( string.Empty, search, null, null, string.Empty);
}
public DataTable Search( string search, string[] roleIds)
{
return Search( string.Empty, search, roleIds, null, string.Empty);
}
public DataTable Search( string search, string[] roleIds, bool? enabled)
{
return Search( string.Empty, search, roleIds, null, string.Empty);
}
public DataTable Search( string search, string[] roleIds, string auditStates)
{
return Search( string.Empty, search, roleIds, null, auditStates);
}
public DataTable Search( string search, string[] roleIds, bool? enabled, string auditStates)
{
return Search( string.Empty, search, roleIds, enabled, auditStates);
}
那采用了缺省参数后,这部分代码会被简化成什么样子了呢?
public DataTable Search(
string search =
null,
string[] roleIds =
null,
bool? enabled =
true,
string auditStates =
null)
{
return Search( string.Empty, search, roleIds, enabled, auditStates);
}
{
return Search( string.Empty, search, roleIds, enabled, auditStates);
}
哇靠,居然一行代码就可以了,那么多构造函数都不需要了, 代码简洁了很多了,清爽了很多,心里也舒畅了.
新技术也往往会明显提高生产效率.
转载于:https://blog.51cto.com/2347979/1197307