在枚举属性的情况下,从 System.Int32 到 Nullable 的转换无效
Invalid cast from System.Int32 to Nullable in case of Enum properties
我有以下静态方法:
public static cols Parse(string[] inCols, int[] dat)
{
cols c = new cols();
PropertyInfo[] properties = typeof(cols).GetProperties();
for (int i = 0; i < inCols.Length; i++)
{
PropertyInfo prop = properties.Single(a => a.Name == inCols[i]);
var t = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
var safeValue = Convert.ChangeType(dat[i], t);
prop.SetValue(c, safeValue);
}
return c;
}
这里,"cols" class 的属性是可为空的枚举类型。
该方法有两个传入参数(inCols 和 dat)。 inCols 包含作为字符串的属性名称,dat 包含它们作为 int 的值。
该方法的任务是根据方法的名称,为可空枚举类型分配适当的值。
我收到以下错误消息:System.InvalidCastException: 'Invalid cast from 'System.Int32' to '<my enum type>'.'
这很奇怪,因为值应该是 0,这对枚举来说很好,因为它是它的第一个值。
你们有什么想法吗?
谢谢!
嘉宝
因为您只处理 Enums
,您可以简单地将代码更改为:
var safeValue = Enum.ToObject(t, dat[i]);
我有以下静态方法:
public static cols Parse(string[] inCols, int[] dat)
{
cols c = new cols();
PropertyInfo[] properties = typeof(cols).GetProperties();
for (int i = 0; i < inCols.Length; i++)
{
PropertyInfo prop = properties.Single(a => a.Name == inCols[i]);
var t = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
var safeValue = Convert.ChangeType(dat[i], t);
prop.SetValue(c, safeValue);
}
return c;
}
这里,"cols" class 的属性是可为空的枚举类型。
该方法有两个传入参数(inCols 和 dat)。 inCols 包含作为字符串的属性名称,dat 包含它们作为 int 的值。
该方法的任务是根据方法的名称,为可空枚举类型分配适当的值。
我收到以下错误消息:System.InvalidCastException: 'Invalid cast from 'System.Int32' to '<my enum type>'.'
这很奇怪,因为值应该是 0,这对枚举来说很好,因为它是它的第一个值。
你们有什么想法吗?
谢谢! 嘉宝
因为您只处理 Enums
,您可以简单地将代码更改为:
var safeValue = Enum.ToObject(t, dat[i]);