如何通过反射将字符串赋值给整型字段

5

这就是让我伤心的代码:

private static void AssignId(object entity, string id)
        {
            var idFieldInfo = entity.GetType().GetProperties().SingleOrDefault(it => it.GetCustomAttributes(typeof(KeyAttribute), false).Any());
            if (idFieldInfo != null)
            {
                var type = idFieldInfo.PropertyType;

                if (type == typeof(byte))
                {
                    idFieldInfo.SetValue(entity, Convert.ToByte(id), null);
                }
                else if (type == typeof(short))
                {
                    idFieldInfo.SetValue(entity, Convert.ToInt16(id), null);
                }
                else if (type == typeof(int))
                {
                    idFieldInfo.SetValue(entity, Convert.ToInt32(id), null);
                }
                else if (type == typeof(long))
                {
                    idFieldInfo.SetValue(entity, Convert.ToInt64(id), null);
                }
                else if (type == typeof(sbyte))
                {
                    idFieldInfo.SetValue(entity, Convert.ToSByte(id), null);
                }
                else if (type == typeof(ushort))
                {
                    idFieldInfo.SetValue(entity, Convert.ToUInt16(id), null);
                }
                else if (type == typeof(uint))
                {
                    idFieldInfo.SetValue(entity, Convert.ToUInt32(id), null);
                }
                else if (type == typeof(ulong))
                {
                    idFieldInfo.SetValue(entity, Convert.ToUInt64(id), null);
                }
            }
        }

有没有更聪明的方法将字符串值分配给对应的整数


1
查看这篇文章,它涵盖了比“ChangeType”更广泛的目标类型,但是你需要自己解析字符串。 - Sergey Kalinichenko
可能是使用反射设置字符串值的属性的重复问题。 - Alena Kastsiukavets
1个回答

10

您可以使用Convert.ChangeType方法。

if (idFieldInfo != null)
{
     var type = idFieldInfo.PropertyType;
     idFieldInfo.SetValue(entity, Convert.ChangeType(id, type), null);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接