【发布时间】:2015-05-29 22:28:31
【问题描述】:
我遇到了与System.Convert(Object value) 方法相关的问题,我的研究使我找到了documentation。
我想知道the reasonsc# 团队做出这个决定的背后是什么,因为这对我来说没有任何意义。
从我的角度来看,最好返回“Null”,请注意这个例子:
static void Main(string[] args)
{
int? ID = null;
string result = Convert.ToString(ID);
Console.WriteLine("{0} ,{1}",result ,result.Length);
Console.ReadKey();
}
//result would be "" and the result.Length=0
如您所见,ID 是 null,但 convert(ID) 不是 null,这听起来很奇怪!!
这是convert(object value)的源代码,我是从这个问题的answer中捡到的。
public static string ToString(Object value) {return ToString(value,null);}
public static string ToString(Object value, IFormatProvider provider) {
IConvertible ic = value as IConvertible;
if (ic != null)
return ic.ToString(provider);
IFormattable formattable = value as IFormattable;
if (formattable != null)
return formattable.ToString(null, provider);
return value == null? String.Empty: value.ToString();
请关注last line。我只是想知道这背后的rational 是什么。
提前谢谢。
编辑
ID.Tostring() 根本没用的情况太多了
例如:
public System.Web.Mvc.ActionResult MyAction(int? Id)
{
//This line of code dosent show "Id has no value" at all
MyContetnt = (System.Convert.ToString(Id) ?? "Id has no value");
return Content(MyContetnt);
}
在此代码示例中,如果您通过此路径运行此 Mvc 示例:
http://localhost: portnumber/ControllerName/MyAction
我的意思是without using ID in the path 你在屏幕上看不到Nothing,因为ID 在这里是null 而Convert.Tostring(ID) 的结果是System.Empty 或“”。
我的意思是在这种情况下,无法使用null-coalescing-operator 重构此代码,使用ID.tostring() 会引发nullrefrenceException,这没有用,也不是我的意图。我知道这很容易说:
MyContent = Id.HasValue ? Id.Value.ToString() : "Id has no value"
// this line works fine;
但是假设convert.ToString(Null) 的结果是Null 那么第一个带有null-coalescing-operator 的代码将完美运行。
所以我很好奇这个想法背后的原因是什么,Convert.tostring (object null) 的结果是string.empty 而不是null?
【问题讨论】:
-
您可以使用 .ToString() 这将引发错误
object reference not set to an instance of an object -
在您的情况下,
string result = (ID).ToString();将返回异常,即object reference not set to an instance of an object -
可能是因为 null 不是字符串,而作者认为 null 最接近的字符串表示形式是空字符串?