﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>IT博客-aser911-文章分类-.Net</title><link>http://www.cnitblog.com/aser911/category/8567.html</link><description /><language>zh-cn</language><lastBuildDate>Tue, 27 Sep 2011 06:54:21 GMT</lastBuildDate><pubDate>Tue, 27 Sep 2011 06:54:21 GMT</pubDate><ttl>60</ttl><item><title>ToString 未将对象引用设置到对象的实例</title><link>http://www.cnitblog.com/aser911/articles/63445.html</link><dc:creator>aser</dc:creator><author>aser</author><pubDate>Tue, 29 Dec 2009 06:38:00 GMT</pubDate><guid>http://www.cnitblog.com/aser911/articles/63445.html</guid><wfw:comment>http://www.cnitblog.com/aser911/comments/63445.html</wfw:comment><comments>http://www.cnitblog.com/aser911/articles/63445.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cnitblog.com/aser911/comments/commentRss/63445.html</wfw:commentRss><trackback:ping>http://www.cnitblog.com/aser911/services/trackbacks/63445.html</trackback:ping><description><![CDATA[<p>&nbsp;</p>
<p>今天调试程序时 出现了未将对象引用设置到对象实例的错误</p>
<p>最后发现错误的原因是对一个string 变量使用ToString方法 而这个变量的值为null</p>
<p>当某个没有值的时候 使用ToString将提示&#8220;使用了未赋值变量&#8220;，可偏偏string可以被赋值为null</p>
<p>如果这个时候又恰巧对string使用了ToString()方法 就出现了这个隐蔽的错误。</p>
<p><br>null 关键字是表示不引用任何对象的 null 引用的文字值。null 是引用类型变量的默认值。普通值类型不能为 null。</p>
<p>但是，C# 2.0 引入了可以为 null 值的类型。请参见可空类型（C# 编程指南）。</p>
<p>int? test=null &nbsp;&nbsp;&nbsp;//是可以<br>string res=test.ToString()&nbsp;//结果为""</p>
<p>但string? test=null;这种定义是不可以的<br>将提示 string必须是不可为空的类型才能用作泛型类型或方法"System.Nullable&lt;T&gt;"中的参数T</p>
<p>所以可空类型 实际上是作为泛型的参数</p>
<p>总之 对于引用类型使用ToString()等方法时 要考虑null的情况。</p>
<img src ="http://www.cnitblog.com/aser911/aggbug/63445.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cnitblog.com/aser911/" target="_blank">aser</a> 2009-12-29 14:38 <a href="http://www.cnitblog.com/aser911/articles/63445.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>