c# - 在扩展方法中处理 null

标签 c# extension-methods

我有一个简单的字符串类扩展方法,它将从字符串中去除所有非数字字符。因此,如果我有一个字符串,例如电话号码,如“(555) 215-4444”,它会将其转换为“5552154444”。它看起来像这样:

public static string ToDigitsOnly(this string input)
{
    Regex digitsOnly = new Regex(@"[^\d]");
    return digitsOnly.Replace(input, String.Empty);
}

我只是想知道在这里处理空值的最优雅的方法是什么?在这些情况下是否有可遵循的典型模式,例如如果传入 null,则返回 null 值?似乎因为我在这里扩展了字符串类,所以我可能希望允许空值并且不抛出争论异常(因为当我使用这个时我并没有真正传递争论......)?但有些人可能会争辩说我应该像“正常”方法那样抛出异常。您在这里使用的最佳做法是什么?

谢谢!

最佳答案

您可以遵循最小意外原则:使用在 LINQ 中实现的模式:

public static string ToDigitsOnly(this string input)
{
    if(input == null)
          throw new ArgumentNullException("input");

    Regex digitsOnly = new Regex(@"[^\d]");
    return digitsOnly.Replace(input, String.Empty);
}

您可以使用方法,proposed by Jon Skeet .它会将您的支票简单地减少到

input.ThrowIfNull("input");

此外,Jon 在 C# 深入研究 中有一个很好的部分10.2.4 在空引用上调用方法,引用:

CHECKING FOR NULLITY As a conscientious developer, I’m sure that your production methods always check their arguments’ validity before proceeding. One question that naturally arises from this quirky feature of extension methods is what exception to throw when the first argument is null (assuming it’s not meant to be). Should it be ArgumentNullException, as if it were a normal argument, or should it be NullReferenceException, which is what would’ve happened if the extension method had been an instance method to start with? I recommend the former: it’s still an argument, even if the extension method syntax doesn’t make that obvious.

我认为这个建议是(根据我的个人经验):检查 null 总是更好,特别是对于静态方法并且不要依赖 null 值。只有当它是您的方法的确切目的时才有异常(exception),例如 ThrowIfNullIsNullOrEmpty 扩展方法。

关于c# - 在扩展方法中处理 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16592029/

相关文章:

c# - 扩展方法和静态方法有什么区别?

c# - 当表单没有焦点时,RichTextBox 不会在按下鼠标时开始选择

c# - 这种技术有名称吗?它是一种代码味道吗?

Rust 等同于 Swift 对协议(protocol)的扩展方法?

ios - 如何创建扩展文件并在 iOS Swift 3 的 View Controller 中调用它?

c# - 使用实时图表创建 WPF C# 图表

c# - SQL Server 一张或两张表?

c# - 阴性测试 - 我应该期待确切的异常(exception)吗?

c# - 继承可选参数基方法的歧义

具有特定类型的 List 上的 C# 扩展方法