扩展方法在同一个扩展类中调用另一个 - 好的设计?

时间:2010-09-16 18:44:04

标签: c# extension-methods

我问自己,如果扩展方法使用它是否是一个好的设计  另一个在同一个扩展类中。

public class ClassExtensions
{
   public static bool IsNotNull<T>(this T source)
      where T : class
   {
      return !source.IsNull();
   }

   public static bool IsNull<T>(this T source)
      where T : class
   {
      return source == null;
   }
}

修改 谢谢你的回答。 对不好的样品感到抱歉。

4 个答案:

答案 0 :(得分:7)

没关系。当然,您的示例有点微不足道,但请考虑其他情况,其中方法可以提供重载(使用string.Substring作为示例...假装方法尚不存在)。

public static class Foo
{
    public static string Substring(this string input, int startingIndex)
    {
         return Foo.Substring(input, startingIndex, input.Length - startingIndex);
         // or return input.Substring(startingIndex, input.Length - startingIndex);
    }

    public static string Substring(this string input, int startingIndex, int length)
    {
         // implementation 
    }
}

调用过载显然可以让您尽可能地集中逻辑,而不必重复自己。在实例方法中确实如此,在静态方法(包括扩展方法,包括扩展方法)中也是如此。

答案 1 :(得分:2)

恕我直言,通常是这样,因为它减少了你必须编写的代码量,从而减少了出错的机会。

然而,在上面的例子中,由于方法的简单性,我认为它是过度的。

答案 2 :(得分:1)

是的,这是一个很好的做法。将该类视为一种命名空间,并将相关的扩展组合在一起。

答案 3 :(得分:0)

当然这是一个很好的设计,可以称为DRY

然而,这是一个非常简单的例子。

相关问题