铸造(INT?)空与新INT() - ?哪个更好? [英] Casting (int?)null vs. new int?() - Which is better?

查看:90
本文介绍了铸造(INT?)空与新INT() - ?哪个更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用可空<装载值到类和结构时种了不少,当我需要他们可以为空,如从数据库中装载一个空值; T> (如下面的例子)

I use Nullable<T> types quite a lot when loading values into classes and structs when I need them to be nullable, such as loading a nullable value from a database (as the example below).

考虑这个代码片段:

public class InfoObject
{
    public int? UserID { get; set; }
}

// Load the ID into an SqlInt32
SqlInt32 userID = reader.GetSqlInt32(reader.GetOrdinal("intUserID"));

当我需要一个值加载到为空的属性,有时候我这样做:

When I need to load a value into a nullable property, sometimes I do this:

infoObject.UserID = userID.IsNull ? (int?)null : userID.Value;



有时候,我这样做,而不是:

Sometimes I do this instead:

infoObject.UserID = userID.IsNull ? new int?() : userID.Value;



虽然他们得到相同的结果,我想看看是否有人知道哪个是更好地使用之间的(INT?)空新的诠释?()与性能有关的,最小的IL代码,最佳实践等?

Although they achieve the same result, I'd like to see if anyone knows which is better to use between (int?)null and new int?() with regards to performance, smallest IL code, best practices etc.?

一般来说,我一直在偏袒新的诠释?()版本上面的代码,但我不敢肯定是否铸造(INT?)空更快的编译器不是解决新的诠释?()

Generally I've been favouring the new int?() version of the code above, but I'm not sure whether casting (int?)null is quicker for the compiler to resolve than new int?().

干杯!

推荐答案

他们会产生相同的IL。无论你找到更轻松的使用阅读。

They will generate the same IL. Use whichever you find easier to read.

当你谈论的东西是更快的编译器来解决你说的是微优化的建立的时间?我不知道这将是快,但我怀疑它将使代码的任何显著的身体可靠的,可测量的差异。

When you talk about something being "quicker for the compiler to resolve" are you talking about micro-optimising your build times? I have no idea which would be faster there, but I doubt it will make a reliably-measurable difference for any significant body of code.

我个人使用无效每当我可以毫不含糊这样做;我想我还是一般喜欢剧组调用,但它并没有真正的区别。

Personally I use null whenever I can do so with no ambiguity; I think I still generally prefer the cast to calling new, but it makes no real difference.

这篇关于铸造(INT?)空与新INT() - ?哪个更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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