繁体   English   中英

如何通过反射将字符串分配给整数字段

[英]How to assign a string to an integer field via reflection

所以这就是令我难过的代码:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM