Home  >  Article  >  Backend Development  >  Detailed explanation of exceptions in C# code Convert.ToChar(null); (picture)

Detailed explanation of exceptions in C# code Convert.ToChar(null); (picture)

黄舟
黄舟Original
2017-03-11 13:12:382467browse

说在前面

<br/>

关于c#代码Convert.ToChar(null);出现异常,而object obj = null; Convert.ToChar(obj);//返回’\0’空字符问题详解。
为什么会想到说这个问题呢?
今天在博乐功能下点评一篇文章“关于System.Convert那些事”中提出了这个问题:

Convert.ToChar(null);

直接这样调用,执行时会产生异常;
而以下代码却不会出现异常!

object obj = null; 
Convert.ToChar(obj);//返回&#39;\0&#39;空字符

异常分析

发生了 System.ArgumentNullException
Detailed explanation of exceptions in C# code Convert.ToChar(null); (picture)

查看详细信息,可以看到异常的具体信息,是在 System.Convert.ToChar(String value, IFormatProvider provider)发生了异常:
Detailed explanation of exceptions in C# code Convert.ToChar(null); (picture)

但通过调用堆栈,我们对错误能更清楚的认识;
如下图,在发生异常的方法之间还有一层调用:
System.Convert.ToChar(string value)
Detailed explanation of exceptions in C# code Convert.ToChar(null); (picture)

System.Convert.ToChar(string value),这才是问题的关键!

当执行Convert.ToChar(obj);时,obj的类型已经明确了是object类型,所以调用的是Convert.ToChar(object value);的实现:

public static char ToChar(object value)
{    if (value != null)
    {        return ((IConvertible) value).ToChar(null);
    }    return &#39;\0&#39;;
}

而执行Convert.ToChar(null);时,null可以赋值给多种数据类型,而编译器在处理时默认把它当作了String类型,所以我们在调用堆栈中看到了中间的一步:System.Convert.ToChar(string value),实现如下:

public static char ToChar(string value)
{    return ToChar(value, null);
}

所以才会在 System.Convert.ToChar(String value, IFormatProvider provider)发生了异常

public static char ToChar(string value, IFormatProvider provider)
{    if (value == null)
    {        throw new ArgumentNullException("value");
    }    if (value.Length != 1)
    {        throw new FormatException(Environment.GetResourceString("Format_NeedSingleChar"));
    }    return value[0];
}

总结

究其原因,是编译器给与“null”的默认数据类型的问题,所以导致看似相同的代码,却产生不同的结果。

这也涉及到多态和重载(多态是面向对象编程思想的一种特征,重载是指方法可以根据不同的参数个数与类型,来实现多种功能,重载方法可以理解成多态的具体表现形式),如果只有Convert.ToChar(object value);这一种实现,也不会产生本文阐述的问题,也不会有本文了。

The above is the detailed content of Detailed explanation of exceptions in C# code Convert.ToChar(null); (picture). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn