示例#1
0
        /// <summary>
        /// 根据JsonElement对象, 设置指定的属性值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="propertyName">属性的名字</param>
        /// <param name="jsonValue">JsonElement 属性值</param>
        /// <remarks>
        /// 属性值运行时类型如果不符合, 将会抛出异常
        /// </remarks>
        public static void Set <T>(this T obj, string propertyName, System.Text.Json.JsonElement jsonValue)
        {
            var pi = obj?.GetType().GetPropertyInfo(propertyName);

            if (pi is null)
            {
                throw new ArgumentOutOfRangeException(propertyName);
            }
            var type = pi.PropertyType;

            if (type == typeof(string))
            {
                pi.SetValue(obj, jsonValue.GetString());
            }
            else if (type == typeof(Int16))
            {
                pi.SetValue(obj, jsonValue.GetInt16());
            }
            else if (type == typeof(Int32))
            {
                pi.SetValue(obj, jsonValue.GetInt32());
            }
            else if (type == typeof(Int64))
            {
                pi.SetValue(obj, jsonValue.GetInt64());
            }
            else if (type == typeof(Single))
            {
                pi.SetValue(obj, jsonValue.GetSingle());
            }
            else if (type == typeof(Double))
            {
                pi.SetValue(obj, jsonValue.GetDouble());
            }
            else if (type == typeof(Decimal))
            {
                pi.SetValue(obj, jsonValue.GetDecimal());
            }
            else if (type == typeof(DateTime))
            {
                pi.SetValue(obj, jsonValue.GetDateTime());
            }
            else if (type == typeof(UInt16?))
            {
                pi.SetValue(obj, jsonValue.GetUInt16());
            }
            else if (type == typeof(UInt32?))
            {
                pi.SetValue(obj, jsonValue.GetUInt32());
            }
            else if (type == typeof(UInt64?))
            {
                pi.SetValue(obj, jsonValue.GetUInt64());
            }
            else if (type == typeof(Boolean))
            {
                pi.SetValue(obj, jsonValue.GetBoolean());
            }
            else if (type == typeof(Byte))
            {
                pi.SetValue(obj, jsonValue.GetByte());
            }
            else if (type == typeof(SByte))
            {
                pi.SetValue(obj, jsonValue.GetSByte());
            }
            else if (type == typeof(Guid))
            {
                pi.SetValue(obj, jsonValue.GetGuid());
            }
            else
            {
                throw new TypeNotSupportException(type);
            }
        }