2012-04-27 97 views
4

所以这是一个让我伤心的代码:如何通过反射一个字符串赋值给一个整数字段

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

退房[本文](http://www.codeproject.com/Articles/61460/Using-LINQ-for-type-conversion),它覆盖除了'一changeType更宽范围的目标类型的',但你会解析str你自己的弦乐。 – dasblinkenlight 2012-04-27 09:52:45

+0

[通过字符串值反射设置属性]的可能重复(https://stackoverflow.com/questions/1089123/setting-a-property-by-reflection-with-a-string-value) – 2017-07-24 11:50:19

回答

10

您可以使用一个字符串值的明智之选Convert.ChangeType

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

哇这一个让我感到非常愚蠢,谢谢 – v00d00 2012-04-27 10:01:31

相关问题