【发布时间】:2020-03-23 18:31:05
【问题描述】:
我有以下静态方法:
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”类的属性是可以为空的枚举类型。
该方法有两个传入参数(inCols 和 dat)。 inCols 包含作为字符串的属性名称,dat 包含作为 int 的值。
该方法的任务是根据方法的名称,为可为空的枚举类型分配适当的值。
我收到以下错误消息:System.InvalidCastException: 'Invalid cast from 'System.Int32' to '<my enum type>'.'
这很奇怪,因为值应该是 0,这对于枚举来说很好,因为它是它的第一个值。
你们有什么想法吗?
谢谢! 加博
【问题讨论】:
标签: c# enums type-conversion nullable