[英]Convert.ToDouble and Double.Parse in C#
I'd like to ask about Convert.ToDouble
and Double.Parse
in C# 我想问一下C#中的Convert.ToDouble
和Double.Parse
When I write this code, it's ok 当我写这段代码时,没关系
static void Main(string[] args)
{
double red;
Console.Write("Red = ");
red = Convert.ToDouble(Console.ReadLine());
}
but if I try 但如果我试试
static void Main(string[] args)
{
double red;
Console.Write("Red = ");
red = Double.Parse(Console.ReadLine());
}
I get caution from ReSharper 'Possible 'null' assignment to entity marked with 'NotNull' attribute'
我对ReSharper 'Possible 'null' assignment to entity marked with 'NotNull' attribute'
感到谨慎
How to fix that? 如何解决?
double
is a value type which cannot be null
. double
是一个不能为null
的值类型 。
double.Parse
will try to parse a string
into a double
. double.Parse
将尝试将string
解析为double
。 It does not try to coerce mismatched values such as null
. 它不会尝试强制不匹配的值,如null
。
Convert.ToDouble
will try to take mismatched strings and find a suitable value. Convert.ToDouble
将尝试获取不匹配的字符串并找到合适的值。 For null
that would be 0.0
. 对于null
为0.0
。
To check if a sting is directly parsable try using double.TryParse
with the appropriate overload. 要检查sting是否可以直接解析,请尝试使用带有适当重载的double.TryParse
。
For example: 例如:
double red;
Console.Write("Red = ");
var input = Console.ReadLine();
if(!double.TryParse(input, out red))
{
Console.WriteLine("You have not entered an appropriate value!");
}
This will try to parse a double using the current Culture and default NumberStyles . 这将尝试使用当前Culture和默认NumberStyles解析double。
Convert.ToDouble
is utility method. Convert.ToDouble
是实用方法。
Convert.ToDouble
documentation explains: Convert.ToDouble
文档说明:
Return Value Type: System.Double A double-precision floating-point number that is equivalent to value, or zero if value is null. 返回值类型:System.Double等价于值的双精度浮点数,如果value为null,则为零。
Double.Parse
will throw ArgumentNullException
if you pass null, since Double
cannot be constructed with null
. 如果传递null, Double.Parse
将抛出ArgumentNullException
,因为Double
不能用null
构造。 Explained here: http://msdn.microsoft.com/en-us/library/fd84bdyt.aspx 这里解释: http : //msdn.microsoft.com/en-us/library/fd84bdyt.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.