Пример #1
0
        /// <summary>
        /// 获取一个对象<see cref="object"/>中指定字段的值
        /// </summary>
        /// <param name="target">要取值的对象<see cref="object"/></param>
        /// <param name="fieldName">要取值的属性/字段名称</param>
        /// <returns></returns>
        public static object Get(object target, string fieldName)
        {
            object result = null;

            if (target == null)
            {
                return(result);
            }
            Type targetType = target.GetType();

            if (targetType.IsValueType || targetType.IsEnum)
            {
                result = null;
            }
            else if (target is IDictionary)
            {
                result = DictionaryUtil.Get(target as IDictionary, fieldName);
            }
            else if (target is DataRow)
            {
                result = RowUtil.Get(target as DataRow, fieldName);
            }
            else if (target is JObject)
            {
                result = Get((target as JObject)[fieldName]);
            }
            else if (targetType.IsClass)
            {
                PropertyInfo property = targetType.GetProperty(fieldName);
                if (property != null)
                {
                    result = property.GetValue(target);
                }
                else
                {
                    FieldInfo field = targetType.GetField(fieldName);
                    if (field != null)
                    {
                        result = field.GetValue(target);
                    }
                }
            }

            if (result != null)
            {
                Type resultType        = result.GetType();
                Type resultGenericType = null;
                if (resultType.IsGenericType)
                {
                    resultGenericType = resultType.GetGenericArguments().FirstOrDefault(); //获取第一个泛型类型
                }
                if (result is JArray || result is ArrayList || (resultGenericType != null && (StringUtil.CompareType(resultGenericType, typeof(JObject)) || resultGenericType.Equals(typeof(object)) /*StringUtil.CompareType(resultGenericType, "System.Object")*/)))
                {
                    IList resultList = result as IList; //处理Json数组
                    resultList = ConvertList(resultList);
                    if (!(target is JObject))
                    {
                        Set(target, fieldName, resultList);
                    }
                    result = resultList;
                }
                else if (result is JObject)
                {
                    result = DictionaryUtil.Convert(result);
                }
            }
            return(result);
        }