System.Nullablenull * int 值的值是多少?
考虑以下陈述:
int? v1 = null;
int? v2 = 5 * v1;
v2
的值是多少? (null
或空字符串?)
如何防止编译器将其标记为无效操作?我需要遵循自定义异常处理吗?
Consider the following statements:
int? v1 = null;
int? v2 = 5 * v1;
What is the value of v2
? (null
or empty string?)
How can I prevent the compiler to mark it as invalid operation? Do I need to follow custom exception handling?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它是
null
。这不是无效操作。它不会抛出异常,因此在这种情况下您不需要处理异常。
It's
null
.It's not an invalid operation. It won't throw an exception so you don't need to handle exceptions in this case.
如果您希望编译器阻止该操作,请将第二个变量设置为不可为 null。那么你将被迫这样写:
如果 v1 为 null,这将在运行时抛出异常。
If you want the operation to be prevented by the compiler, make the second variable non-nullable. Then you will be forced to write:
This will throw an exception at run time if v1 is null.
它的值将是“null”,在这种情况下至少可以被认为与数据库null相同,即而不是Nothing或Zero,它意味着“Unknown”。五批未知仍然是未知,它也永远不会是“空字符串”,因为您处理的是数字,而不是字符串。
我不确定“如何防止编译器将其标记为无效操作?”是什么意思?因为这段代码在 Visual Studio 2008 下编译并运行良好 =)
Its value will be "null", in this context at least can be considered to be the same as a database null, i.e. rather than Nothing, or Zero, it means "Unknown". Five lots of Unknown is still Unknown, it'll also never be "empty string" as you're dealing with numbers, not strings.
I'm not sure what you mean by "How can I prevent the compiler to mark it as invalid operation?" as this code compiles and runs fine for me under Visual Studio 2008 =)
我不确定你想做什么,但如果你希望 v2 为空(如果 v1 为空),那么你应该在使用 v1 之前测试它是否有值。
或者
I'm not sure what you are trying to do, but if you want v2 to be null if v1 is null then you should test if v1 has a value prior to using it.
or