也许这是一个简单的问题,但我已经尝试了所有的转换方法!它仍然有错误!你能帮我吗?
将 nullable decimal(可空十进制数) 转换为 decimal(十进制数)
也许这是一个简单的问题,但我已经尝试了所有的转换方法!它仍然有错误!你能帮我吗?
将 nullable decimal(可空十进制数) 转换为 decimal(十进制数)
有很多选择...
decimal? x = ...
decimal a = (decimal)x; // works; throws if x was null
decimal b = x ?? 123M; // works; defaults to 123M if x was null
decimal c = x.Value; // works; throws if x was null
decimal d = x.GetValueOrDefault(); // works; defaults to 0M if x was null
decimal e = x.GetValueOrDefault(123M); // works; defaults to 123M if x was null
object o = x; // this is not the ideal usage!
decimal f = (decimal)o; // works; throws if x was null; boxes otherwise
尝试使用??
运算符:
decimal? value=12;
decimal value2=value??0;
当 decimal?
为 null 时,您想要的值是 0。
您不需要将可空类型转换为获取其值。
您只需利用 Nullable<T>
公开的 HasValue
和 Value
属性即可。
例如:
Decimal? largeValue = 5830.25M;
if (largeValue.HasValue)
{
Console.WriteLine("The value of largeNumber is {0:C}.", largeValue.Value);
}
else
{
Console.WriteLine("The value of largeNumber is not defined.");
}
或者,你可以在C# 2.0或更高版本中使用null合并运算符作为快捷方式。
如果decimal?
是null
,那么这取决于你想做什么,因为decimal
不能为null
。如果你想将其默认为0,可以使用以下代码(使用空合并运算符):
decimal? nullabledecimal = 12;
decimal myDecimal = nullabledecimal ?? 0;
您可以使用以下代码:
decimal? v = 2;
decimal v2 = Convert.ToDecimal(v);
如果值为 null(v),则会被转换为 0。
GetValueOrDefault
,因为它不依赖于C#语法,因此也可以在VB.NET中使用。如果类型的默认值对您不起作用,它也很容易进行调整。 - Victor Zakharov