Neg*_*gar 48 .net c# nullable decimal type-conversion
可能是一个简单的问题,但我尝试了所有的转换方法!它仍然有错误!你能帮我吗?
十进制?(可以为十进制)到十进制
Mar*_*ell 102
有很多选择......
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
Run Code Online (Sandbox Code Playgroud)
Car*_*any 29
尝试使用??
运算符:
decimal? value=12;
decimal value2=value??0;
Run Code Online (Sandbox Code Playgroud)
0 decimal?
是null 时所需的值.
Cod*_*ray 12
您无需转换可空类型即可获取其值.
您只需走的优势HasValue
和Value
通过公开的属性Nullable<T>
.
例如:
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.");
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用C#2.0或更高版本中的空合并运算符作为快捷方式.
decimal?
这取决于如果 a是的话你想做什么null
,因为 adecimal
不能是null
。如果您想将其默认为 0,可以使用以下代码(使用空合并运算符):
decimal? nullabledecimal = 12;
decimal myDecimal = nullabledecimal ?? 0;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
67871 次 |
最近记录: |