C# 问号运算符后缀进行强制转换
我正在查看 dapper 页面,看到了这段简短的编码:
new { Age = (int?)null, Id = guid });
什么(int?)null
可以吗?
有人可以解释一下那里发生了什么,也许可以给出更“详细”的代码版本吗?
I was looking at the dapper page and saw this terse bit of coding:
new { Age = (int?)null, Id = guid });
What does (int?)null
do?
Could someone please elucidate what is going on there, and perhaps give a more "verbose" version of the code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
int?
是Nullable
的简写。因此,这行代码将 null (默认情况下为object
类型)转换为 null int。文档:http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx
int?
is shorthand forNullable<int>
. as such this line of code is converting null (which by default is of typeobject
) to a null int.Docs: http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx
如果您拥有的只是
new { Age = null }
,编译器无法知道Age
的确切类型是什么。因此,将null
转换为Nullable
有效地告诉它Age
属性属于该类型。If all you have is
new { Age = null }
, compiler has no way of knowing what is the exact type ofAge
. So "casting"null
toNullable<Int32>
effectively tells it thatAge
property is of that type.这是一个匿名类型:
年龄 必须从分配给它的值中隐含。
null
可以是任何可为空的类型。强制转换指定Age
应具有的类型:int?
(又名Nullable
)This is an anonymous type: The type of
Age
must be implied from the value assigned to it.null
can be any nullable type. The cast specify the type thatAge
should have:int?
(akaNullable<int>
)?
标记 < code>Nullable int它是
((System.Nullable)null)
的语法简写。?
marks aNullable
intIt is a syntactical shorhand for
((System.Nullable<int>)null)
.