什么是延长空检查的最佳方式? [英] What is the best way to extend null check?

查看:197
本文介绍了什么是延长空检查的最佳方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您所有这样做:

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

    // Main code.
}



乔恩斯基特曾经提到,他有时会使用扩展做此项检查,以便您可以做:

Jon Skeet once mentioned that he sometimes uses the extension to do this check so you can do just:

parameter.ThrowIfNull("parameter");



所以我来的这个扩展的两个实现,我不知道哪一个是最好的

So I come of with two implementations of this extension and I don't know which one is the best.

首先:

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



二:

Second:

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



你觉得呢?

What do you think?

推荐答案

我会使用内部静态无效ThrowIfNull< T>(这件T 0,串paramName配置)其中T:类 。我不会用内部静态无效ThrowIfNull(该对象o,串paramName配置),因为它可能会做拳击。

I'd use internal static void ThrowIfNull<T>(this T o, string paramName) where T : class. I won't use internal static void ThrowIfNull(this object o, string paramName) because it might do boxing.

这篇关于什么是延长空检查的最佳方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆