c# - 扩展空检查的最佳方法是什么?

标签 c# null extension-methods isnull

你们都这样做:

public void Proc(object parameter)
{
    if (parameter == null)
        throw new ArgumentNullException("parameter");

    // Main code.
}

Jon Skeet 曾经提到他有时会使用扩展程序来执行此检查,因此您只需:

parameter.ThrowIfNull("parameter");

所以我想出了这个扩展的两个实现,但我不知道哪个是最好的。

首先:

internal static void ThrowIfNull<T>(this T o, string paramName) where T : class
{
    if (o == null)
        throw new ArgumentNullException(paramName);
}

第二个:

internal static void ThrowIfNull(this object o, string paramName)
{
    if (o == null)
        throw new ArgumentNullException(paramName);
}

你怎么看?

最佳答案

我倾向于坚持无处不在的Guard为此类:

static class Guard
{
    public static void AgainstNulls(object parameter, string name = null)
    {
        if (parameter == null) 
            throw new ArgumentNullException(name ?? "guarded argument was null");

        Contract.EndContractBlock(); // If you use Code Contracts.
    }
}

Guard.AgainstNulls(parameter, "parameter");

并避免扩展 object , 加上肉眼可见的方法调用 null object 看起来很荒谬(尽管我知道对扩展方法进行空方法调用是完全有效的)。

至于哪个最好,我都不用。 它们都有无限递归。我也不会费心保护消息参数,可以选择将其设置为 null。您的第一个解决方案也不支持 Nullable<T>类型为 class约束阻止它。

我们的 Guard类也有 Contract.EndContractBlock() 当我们决定启用代码契约时调用它,因为它符合所需的“if-then-throw”结构。

这也是 PostSharp aspect 的完美候选者.

关于c# - 扩展空检查的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11522104/

相关文章:

c# - 使用 JavaScriptSerializer 反序列化 JSON

c# - 在不选择日期的情况下从日历控件获取值

java - 什么时候将 object 设置为 null 比较好。 (JSF)。

c# - 如何解决我的扩展库中的扩展方法歧义错误?

c# - 从程序集 Microsoft.IdentityModel.Protocols 派生的方法 'GetBaseConfigurationAsync' 无法减少访问

c# - 解析 CSS 类,但忽略 @media 查询

MySQL 格式化字符串或在 NULL 上返回空字符串

c++ - 在 C/C++ 中为数组参数传递 NULL

c# - 具有可选泛型参数的扩展方法

.net - 用单行求和 TimeSpan 数组?