【问题标题】:Optional Parameters with method overloding方法重载的可选参数
【发布时间】:2013-06-06 16:53:18
【问题描述】:

我有这样的方法:

public static void Fill<T> (this DropDownList control,
   Expression<Func<T, object>> value,      
   Expression<Func<T, bool>> whereClause = null,
   Expression<Func<T, object>> orderClause = null,
   string selectedvalue = null) where T : class
{}

到目前为止一切顺利... 但是我需要在 Where 和 Order 子句中添加 List 选项,所以我添加了更多 3 个新方法:

public static void Fill<T> (this DropDownList control,
   Expression<Func<T, object>> value,      
   IList<Expression<Func<T, bool>>> listWhereClause = null,
   IList<Expression<Func<T, object>>> listOrderClause = null,
   string selectedvalue = null) where T : class
{}

public static void Fill<T> (this DropDownList control,
   Expression<Func<T, object>> value,      
   IList<Expression<Func<T, bool>>> listWhereClause = null,
   Expression<Func<T, object>>> orderClause = null,
   string selectedvalue = null) where T : class
{}

public static void Fill<T> (this DropDownList control,
   Expression<Func<T, object>> value,      
   Expression<Func<T, bool>>> whereClause = null,
   IList<Expression<Func<T, object>>> listOrderClause = null,
   string selectedvalue = null) where T : class
{}

问题是现在我得到了不明确的调用错误... 解决这个问题的最佳选择是什么(不增加方法数)?

【问题讨论】:

  • 您是否有理由不想让调用者自己调用SelectWhereOrderBy 等来生成查询?为什么要抓住所有这样的表达呢?看起来麻烦多于其价值,并且会大大降低过程中的可读性。
  • 1.没有 C# 4.5,您可能会混淆 C# 5.0 和 .Net 4.5。 2.这不是C# 5.0特有的,可选参数是在C# 4.0中添加的。

标签: c# c#-4.0 optional-parameters


【解决方案1】:

删除重载的默​​认值 (null)。因为您添加了默认 null 值的重载,所以编译器根本不知道该使用哪一个。

【讨论】:

  • 另一种选择是(不要开枪)对空值进行类型转换,例如。 (Expression&lt;Func&lt;T, bool&gt;&gt;&gt;)null
  • 更不用说一般情况下您不应该真正使用空集合;你会想要空的集合。
  • 但是 order 和 where 子句必须是可选的......要删除它,我需要创建其他几个重载方法,对吧?
  • @Paul 这一切都取决于,那里肯定有太多混合的东西(至少对我来说):带有许多可选参数的耦合(类似)重载。考虑这个方法调用:DropDownList.Fill&lt;T&gt;(Expression&lt;Func&lt;T, object&gt;&gt;, IList&lt;Expression&lt;Func&lt;T, bool&gt;&gt;&gt;) 在这种情况下应该使用哪一个(第一个或第二个重载)?
  • @Paul 考虑用例和参数之间的差异,然后重构您的方法。您总是可以提供更通用的方法,可以在更专业的方法中使用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-10
  • 1970-01-01
相关资源
最近更新 更多