Khh*_*Khh 9 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;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑 感谢您的回答.对不好的样品感到抱歉.
没关系.当然,您的示例有点微不足道,但请考虑其他情况,其中方法可以提供重载(使用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
}
}
Run Code Online (Sandbox Code Playgroud)
调用过载显然可以让您尽可能地集中逻辑,而不必重复自己.在实例方法中确实如此,在静态方法(包括扩展方法,包括扩展方法)中也是如此.