为什么 .ToString() 在空字符串上导致空错误,当 .ToString() 在具有空值的可空整数上正常工作时?

Why does .ToString() on a null string cause a null error, when .ToString() works fine on a nullable int with null value?(为什么 .ToString() 在空字符串上导致空错误,当 .ToString() 在具有空值的可空整数上正常工作时?) - IT屋-程序员软件开发技术
本文介绍了为什么 .ToString() 在空字符串上导致空错误,当 .ToString() 在具有空值的可空整数上正常工作时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

selectedItem 有两个字段:

  • int?_成本
  • string _serialNumber

在这个例子中,selectedItem_cost_serialNumber 都为 null.我正在通过它们的属性阅读 selectedItem 的字段,并用它们的值填充文本框,当...

In this example, _cost and _serialNumber of selectedItem are BOTH null. I am reading through the fields of selectedItem via their properties, and filling in textboxes with their values, when...

TextBox1.Text = selectedItem.Cost.ToString(); //no error
TextBox2.Text = selectedItem.SerialNumber.ToString(); //error

我知道 SerialNumber.ToString() 是多余的(因为它已经是一个字符串),但我不明白为什么会导致这个异常:

I understand that SerialNumber.ToString() is redundant (because it is already a string), but I don't understand why this causes this exception:

可空对象必须有值.

  • int?_cost 可以为空,并且没有值,但它没有给我例外.
  • string _serialNumber 可以为空,并且没有值,但它确实给了我例外.
    • int? _cost is nullable, and does not have a value, yet it does not give me the exception.
    • string _serialNumber is nullable, and does not have a value, yet it does give me the exception.
    • 这个问题触及它,这家伙本质上在问同样的事情,但有没有指定的答案,它也没有解释为什么可以为 null int?例如,我可以在可空 int 上使用 .ToString() 而不是在空字符串上使用吗?

      This question touches on it, the guy is essentially asking the same thing, but there is no designated answer, and it also doesn't explain why a nullable int? For example, can I use .ToString() on a nullable int but not on a null string?

      推荐答案

      因为 string 类型的 null 真的指向空,所以内存中没有任何对象.
      但是 int? type(nullable) 即使将值设置为 null 仍然指向某个对象.
      如果您阅读 Jeffrey Richter 的CLR via C#"你会发现可空类型只是普通类型的外观类,带有一些封装的逻辑,以便更方便地使用 DB null.

      Because string type's null really points to nothing, there isn't any object in memory.
      But int? type(nullable) even with value set to null still points to some object.
      If you read Jeffrey Richter's "CLR via C#" you'll find out that nullable type are just facade classes for common types with some incapsulated logics in order to make work with DB null more convenient.

      查看 msdn 以了解可空类型.

      Check msdn to learn about nullable types.

      这篇关于为什么 .ToString() 在空字符串上导致空错误,当 .ToString() 在具有空值的可空整数上正常工作时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

      本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

ActiveDirectory error 0x8000500c when traversing properties(遍历属性时 ActiveDirectory 错误 0x8000500c)
search by samaccountname with wildcards(使用通配符按 samaccountname 搜索)
Get the list of Groups for the given UserPrincipal(获取给定 UserPrincipal 的组列表)
Can you find an Active Directory User#39;s Primary Group in C#?(你能在 C# 中找到 Active Directory 用户的主要组吗?)
Query From LDAP for User Groups(从 LDAP 查询用户组)
How can I get DOMAINUSER from an AD DirectoryEntry?(如何从 AD DirectoryEntry 获取 DOMAINUSER?)