【问题标题】:Invalid cast from System.Int32 to Nullable in case of Enum properties在枚举属性的情况下,从 System.Int32 到 Nullable 的无效转换
【发布时间】: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 '&lt;my enum type&gt;'.'

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

你们有什么想法吗?

谢谢! 加博

【问题讨论】:

标签: c# enums type-conversion nullable


【解决方案1】:

因为您只处理Enums,您可以简单地将您的代码更改为:

var safeValue = Enum.ToObject(t, dat[i]);

【讨论】:

    猜你喜欢
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多