我有一些带有一些属性的类,我想将值从字符串转换为该属性的类型。我在转换为可为空类型时遇到问题。这是我的转换方法:
public static object ChangeType(object value, Type type)
{
if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
if (value == null)
{
return null;
}
var underlyingType = Nullable.GetUnderlyingType(type);
var val = Convert.ChangeType(value, underlyingType);
var nullableVal = Convert.ChangeType(val, type); // <-- Exception here
return nullableVal;
}
return Convert.ChangeType(value, type);
}
我收到这样的异常(对于 int 类型的属性?):
从 'System.Int32' 到 'System.Nullable`1 的转换无效[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089]]'。
如何从类型转换为可空类型?
谢谢。
这是不可能的......值类型的装箱“擦除”了Nullable<>
part...
int? num = 5;
object obj = num;
Console.WriteLine(obj.GetType()); // System.Int32
and
int? num = null;
object obj = num;
Console.WriteLine(obj == null); // True
请注意,这个特性使得Nullable<>
“特别的”。他们需要来自 CLR 的直接支持。Nullable<>
不仅仅是您可以编写的结构。
你可以做什么:
public static object ChangeType(object value, Type type)
{
// returns null for non-nullable types
Type type2 = Nullable.GetUnderlyingType(type);
if (type2 != null)
{
if (value == null)
{
return null;
}
type = type2;
}
return Convert.ChangeType(value, type);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)