在C#中,应在支票引用传递给对空方法呢? [英] In C#, should one check references passed to methods against null?

查看:215
本文介绍了在C#中,应在支票引用传递给对空方法呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好了,几个月前我问<一个href=\"http://stackoverflow.com/questions/4390007/in-either-c-or-c-should-i-check-pointer-parameters-for-null\">a关于C和C ++ 类似的问题,但我一直比较注重C#最近,由于整个Windows手机的事情。

Well, a few months ago I asked a similar question about C and C++, but I've been paying more attention to C# lately due to the whole "Windows Phone" thing.

所以,在C#中,应在懒得核对NULL在方法的边界呢?我认为这是比C和C不同++,因为在C#一个大致可以判断一个给定的参考是否有效 - 编译器将prevent一个来自任何地方通过未初始化的引用,因此,剩下的唯一可能的错误是它为空。此外,还有的.NET框架中定义这些东西具体的异常,<一个href=\"http://msdn.microsoft.com/en-us/library/system.argumentnullexception.aspx\">ArgumentNullException,这似乎编纂什么程序员认为当一个无效的空传递,他们应该得到。

So, in C#, should one bother to check against NULL at method boundaries? I think this is different than in C and C++, because in C# one generally can determine whether a given reference is valid -- the compiler will prevent one from passing uninitialized references anywhere, and therefore the only remaining possible mistake is for it to be null. Furthermore, there's a specific exception defined inside the .NET Framework for these things, the ArgumentNullException, which seems to codify what programmers think they should be getting when an invalid null was passed.

我个人的看法再次是主叫方这样做坏了,而上述主叫方应该在他们身上,直到世界末日NRE费用。不过,我对此肯定远远低于我在本地code的土地 - C#有相当的地方不同的编程风格在这方面相比,无论C或C ++

My personal opinion is once again that a caller doing this is broken, and that said caller should have NREs thrown at them until the end of days. However, I'm much less sure about this than I am in native code land -- C# has quite a different programming style in places compared to either C or C++ in this regard.

所以...你应该检查在C#中的方法空参数?

So... should you check for null parameters in C# methods?

推荐答案

是的,检查他们。 preferably使用code合同来告诉您需要非空参数调用者

Yes, check for them. Preferably use Code Contracts to tell the caller that you require non-null parameters

void Foo(Bar bar) {
    Contract.Requires(bar != null);
}

这是特别有利的,因为客户可以清楚地看到什么是需要的参数。

This is particularly advantageous since the client can see exactly what is required of parameters.

如果您不能使用code合同,使用保护条款

If you can't use Code Contracts, use a guard clause

void Foo(Bar bar) {
    Guard.Against<ArgumentNullException>(bar == null);
}

快速失败。

这篇关于在C#中,应在支票引用传递给对空方法呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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