2011-02-02 40 views

回答

3

这取决于你想要如果decimal?做的是null,因为decimal不能null。如果你想默认是0,你可以使用此代码(使用空合并运算符):

decimal? nullabledecimal = 12; 

decimal myDecimal = nullabledecimal ?? 0; 
22

尝试使用??操作:

decimal? value=12; 
decimal value2=value??0; 

0是你想要的值当decimal?为空时。

10

您不需要转换为可以为空的类型以获取其值。

您只需利用Nullable<T>公开的HasValueValue属性。

例如:

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."); 
} 

或者,也可以使用在null coalescing operator C#2.0或更高作为快捷方式。

-2

您可以使用。

decimal? v = 2;

decimal v2 = Convert.ToDecimal(v);

如果值为null(V),它将被转换为0

+0

我认为Convert.ToDecimal()是字符串表示,不用于将可空的十进制转换为十进制。请参阅此处:https://msdn.microsoft.com/en-us/library/9k6z9cdw(v=vs.110).aspx – 2016-02-16 16:17:08

79

有大量的选项...

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 
+1

+1。我更喜欢'GetValueOrDefault`,因为它不依赖于C#语法,因此也可以在VB.NET中使用。如果该类型的默认值不适用于您,它也很容易调整。 – Neolisk 2014-04-15 18:50:05

相关问题