c# 利用反射設置屬性值


        /// <summary>
          /// 設置相應屬性的值
          /// </summary>
          /// <param name="entity">實體</param>
          /// <param name="fieldName">屬性名</param>
          /// <param name="fieldValue">屬性值</param>
          public static void SetValue(object entity, string fieldName, string fieldValue)
          {
              Type entityType = entity.GetType();
 
             PropertyInfo propertyInfo = entityType.GetProperty(fieldName);
 
             if (IsType(propertyInfo.PropertyType, "System.String"))
             {
                 propertyInfo.SetValue(entity, fieldValue, null);
 
             }
 
             if (IsType(propertyInfo.PropertyType, "System.Boolean"))
             {
                 propertyInfo.SetValue(entity, Boolean.Parse(fieldValue), null);
 
             }
 
             if (IsType(propertyInfo.PropertyType, "System.Int32"))
             {
                 if (fieldValue != "")
                     propertyInfo.SetValue(entity, int.Parse(fieldValue), null);
                 else
                     propertyInfo.SetValue(entity, 0, null);
 
            }
 
             if (IsType(propertyInfo.PropertyType, "System.Decimal"))
             {
                 if (fieldValue != "")
                     propertyInfo.SetValue(entity, Decimal.Parse(fieldValue), null);
                 else
                     propertyInfo.SetValue(entity, new Decimal(0), null);
 
             }
 
             if (IsType(propertyInfo.PropertyType, "System.Nullable`1[System.DateTime]"))
             {
                 if (fieldValue != "")
                 {
                    try
                     {
                         propertyInfo.SetValue(
                             entity,
                             (DateTime?)DateTime.ParseExact(fieldValue, "yyyy-MM-dd HH:mm:ss", null), null);
                     }
                     catch
                     {
                         propertyInfo.SetValue(entity, (DateTime?)DateTime.ParseExact(fieldValue, "yyyy-MM-dd", null), null);
                     }
                 }
                 else
                     propertyInfo.SetValue(entity, null, null);
 
             }
 
         }

 

 

         /// <summary>
         /// 類型匹配
         /// </summary>
         /// <param name="type"></param>
         /// <param name="typeName"></param>
         /// <returns></returns>
         public static bool IsType(Type type, string typeName)
         {
             if (type.ToString() == typeName)
                 return true;
             if (type.ToString() == "System.Object")
                 return false;
 
             return IsType(type.BaseType, typeName);
         }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM