C# 如何通过反射将字符串指定给整数字段

C# 如何通过反射将字符串指定给整数字段,c#,C#,这就是让我伤心的代码: private static void AssignId(object entity, string id) { var idFieldInfo = entity.GetType().GetProperties().SingleOrDefault(it => it.GetCustomAttributes(typeof(KeyAttribute), false).Any()); if (idFieldIn

这就是让我伤心的代码:

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);
                }
            }
        }

是否有一种更智能的方法来分配与整数对应的字符串值

您可以使用
Convert.ChangeType

if (idFieldInfo != null)
{
     var type = idFieldInfo.PropertyType;
     idFieldInfo.SetValue(entity, Convert.ChangeType(id, type), null);
}
请检查,它比
ChangeType
涵盖的目标类型范围更广,但是您可以自己解析字符串。可能是字符串的重复