你们都这样做:
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/