码迷,mamicode.com
首页 > Windows程序 > 详细

C# 利用反射动态将字符串转换成属性对应的类型值

时间:2016-05-14 21:41:30      阅读:1880      评论:0      收藏:0      [点我收藏+]

标签:

    /// <summary>
    /// 为指定对象分配参数
    /// </summary>
    /// <typeparam name="T">对象类型</typeparam>
    /// <param name="dic">字段/值</param>
    /// <returns></returns>
    private T Assign<T>(Dictionary<string, string> dic) where T : new()
    {
      Type t = typeof (T);
      T entity = new T();
      var fields = t.GetProperties();
      
      string val = string.Empty;
      object obj = null;
      foreach (var field in fields)
      {
        if (!dic.Keys.Contains(field.Name))
          continue;
        val = dic[field.Name];
        //非泛型
        if (!field.PropertyType.IsGenericType)
          obj = string.IsNullOrEmpty(val) ? null : Convert.ChangeType(val, field.PropertyType);
        else //泛型Nullable<>
        {
          Type genericTypeDefinition = field.PropertyType.GetGenericTypeDefinition();
          if (genericTypeDefinition == typeof (Nullable<>))
          {
            obj = string.IsNullOrEmpty(val) ? null : Convert.ChangeType(val, Nullable.GetUnderlyingType(field.PropertyType));
          }
        }
        field.SetValue(entity, obj, null);
      }

      return entity;
    }    

 

C# 利用反射动态将字符串转换成属性对应的类型值

标签:

原文地址:http://www.cnblogs.com/feiyuhuo/p/5493354.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!