在枚举属性的情况下,从System.Int32强制转换为Nullable

问题描述 投票:0回答:1

我有以下静态方法:

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”类的属性是可为空的Enum类型。该方法有两个传入参数(inCols和dat)。 inCols以字符串形式包含属性名称,而dat以int形式包含其值。方法的任务是根据方法的名称,它为可为空的枚举类型分配适当的值。我收到以下错误消息:System.InvalidCastException: 'Invalid cast from 'System.Int32' to '<my enum type>'.'

这很奇怪,因为该值应该为0,这对于枚举是很好的,因为它是它的第一个值。

你们有什么想法吗?

谢谢!Gabor

c# enums type-conversion nullable
1个回答
0
投票

由于只处理Enums,您可以简单地将代码更改为此:

var safeValue = Enum.ToObject(t, dat[i]);
© www.soinside.com 2019 - 2024. All rights reserved.