C# 将对象转换为十进制?(可为空的十进制)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/527453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cast object to decimal? (nullable decimal)
提问by Natrium
If have this in the setter of a property:
如果在属性的设置器中有这个:
decimal? temp = value as decimal?;
value = "90"
值 = "90"
But after the cast, temp is null...
但是在演员之后, temp 为空......
What is the proper way to do this cast?
做这个演员的正确方法是什么?
采纳答案by Konrad Rudolph
Unboxing only works if the type is identical! You can't unbox an object
that does not contain the target value. What you need is something along the lines of
拆箱仅在类型相同时才有效!您不能拆箱object
不包含目标值的。你需要的是类似的东西
decimal tmpvalue;
decimal? result = decimal.TryParse((string)value, out tmpvalue) ?
tmpvalue : (decimal?)null;
This looks whether the value is parsable as a decimal
. If yes, then assign it to result
; else assign null
. The following code does approximately the same and might be easier to understand for people not familiar with the conditional operator ?:
:
这会查看该值是否可解析为decimal
. 如果是,则将其分配给result
; 否则分配null
. 以下代码大致相同,对于不熟悉条件运算符的人来说可能更容易理解?:
:
decimal tmpvalue;
decimal? result = null;
if (decimal.TryParse((string)value, out tmpvalue))
result = tmpvalue;
回答by StevenMcD
and if you use decimal? temp = (decimal?)value;
如果你使用 decimal? temp = (decimal?)value;
回答by thinkbeforecoding
you should parse the decimal. But if you want your decimal to be null when the string is not correct, use TryParse :
你应该解析十进制。但是,如果您希望在字符串不正确时十进制为空,请使用 TryParse :
decimal parsedValue;
decimal? temp = decimal.TryParse(value, out parsedValue)
? value
: (decimal?)null;
This way you will avoid exceptions while parsing ill formated strings.
这样,您将在解析格式错误的字符串时避免异常。
Almost all primitive types provide a Parse and TryParse methods to convert from string.
几乎所有原始类型都提供了 Parse 和 TryParse 方法来从字符串转换。
Is is also recommended to pass a culture for the provider argument to the method to avoid problems with the decimal separator. If you're reading from another system, CultureInfo.InvariantCulture is probably the way to go (but it's not the default).
还建议将 provider 参数的区域性传递给方法,以避免小数点分隔符出现问题。如果您正在从另一个系统阅读,则 CultureInfo.InvariantCulture 可能是可行的方法(但它不是默认设置)。
bool TryParse(string s, NumberStyles style,
IFormatProvider provider, out decimal result)
回答by Stephen Drew
If you do not want to parse strings, but want to ensure that you receive either null
, a decimal
or a nullable decimal
, then you could do something like this:
如果您不想解析字符串,但想确保您收到null
adecimal
或 nullable decimal
,那么您可以执行以下操作:
public static Nullable<T> Convert<T>(object input)
where T : struct
{
if (input == null)
return null;
if (input is Nullable<T> || input is T)
return (Nullable<T>)input;
throw new InvalidCastException();
}
You could make it return null on the last line instead if you wished to avoid exceptions, although this would not distinguish between real null values and bad casts.
如果您希望避免异常,您可以让它在最后一行返回 null,尽管这不会区分真正的 null 值和错误的强制转换。
Note that you have to use the "is" operator, as the "as" operator does not work on value types, and casting without checking may thrown an InvalidCastException.
请注意,您必须使用“is”运算符,因为“as”运算符不适用于值类型,并且在不检查的情况下进行转换可能会引发 InvalidCastException。
You could also make it an extension method:
您也可以将其设为扩展方法:
public static class ObjectExtensions
{
public static Nullable<T> ToNullable<T>(this object input)
where T : struct
{
if (input == null)
return null;
if (input is Nullable<T> || input is T)
return (Nullable<T>)input;
throw new InvalidCastException();
}
}
And use it like this:
并像这样使用它:
object value = 123.45m;
decimal? dec = value.ToNullable<decimal>();
This will help avoid code contract warnings about unboxing null references.
这将有助于避免有关取消装箱空引用的代码合同警告。