(精华)2020年6月27日 C#类库 object(扩展方法)

using Newtonsoft.Json;
using System;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace Core.Util
{
     
    public static partial class Extention
    {
     
        /// 
        /// 构造函数
        /// 
        static Extention()
        {
     
            JsonSerializerSettings setting = new JsonSerializerSettings();
            JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() =>
            {
     
                //日期类型默认格式化处理
                setting.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
                setting.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                return setting;
            });
        }

        private static BindingFlags _bindingFlags {
      get; }
            = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static;

        /// 
        /// 将一个object对象序列化,返回一个byte[]         
        ///  
        /// 能序列化的对象
        ///  
        public static byte[] ToBytes(this object obj)
        {
     
            using (MemoryStream ms = new MemoryStream())
            {
     
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(ms, obj);
                return ms.GetBuffer();
            }
        }

        /// 
        /// 判断是否为Null或者空
        /// 
        /// 对象
        /// 
        public static bool IsNullOrEmpty(this object obj)
        {
     
            if (obj == null)
                return true;
            else
            {
     
                string objStr = obj.ToString();
                return string.IsNullOrEmpty(objStr);
            }
        }

        /// 
        /// 将对象序列化成Json字符串
        /// 
        /// 需要序列化的对象
        /// 
        public static string ToJson(this object obj)
        {
     
            return JsonConvert.SerializeObject(obj);
        }

        /// 
        /// 实体类转json数据,速度快
        /// 
        /// 实体类
        /// 
        public static string EntityToJson(this object t)
        {
     
            if (t == null)
                return null;
            string jsonStr = "";
            jsonStr += "{";
            PropertyInfo[] infos = t.GetType().GetProperties();
            for (int i = 0; i < infos.Length; i++)
            {
     
                jsonStr = jsonStr + "\"" + infos[i].Name + "\":\"" + infos[i].GetValue(t).ToString() + "\"";
                if (i != infos.Length - 1)
                    jsonStr += ",";
            }
            jsonStr += "}";
            return jsonStr;
        }

        /// 
        /// 深复制
        /// 
        /// 类型
        /// 对象
        /// 
        public static T DeepClone<T>(this T obj) where T : class
        {
     
            if (obj == null)
                return null;

            return obj.ToJson().ToObject<T>();
        }

        /// 
        /// 将对象序列化为XML字符串
        /// 
        /// 对象类型
        /// 对象
        /// 
        public static string ToXmlStr<T>(this T obj)
        {
     
            var jsonStr = obj.ToJson();
            var xmlDoc = JsonConvert.DeserializeXmlNode(jsonStr);
            string xmlDocStr = xmlDoc.InnerXml;

            return xmlDocStr;
        }

        /// 
        /// 将对象序列化为XML字符串
        /// 
        /// 对象类型
        /// 对象
        /// 根节点名(建议设为xml)
        /// 
        public static string ToXmlStr<T>(this T obj, string rootNodeName)
        {
     
            var jsonStr = obj.ToJson();
            var xmlDoc = JsonConvert.DeserializeXmlNode(jsonStr, rootNodeName);
            string xmlDocStr = xmlDoc.InnerXml;

            return xmlDocStr;
        }

        /// 
        /// 是否拥有某属性
        /// 
        /// 对象
        /// 属性名
        /// 
        public static bool ContainsProperty(this object obj, string propertyName)
        {
     
            return obj.GetType().GetProperty(propertyName, _bindingFlags) != null;
        }

        /// 
        /// 获取某属性值
        /// 
        /// 对象
        /// 属性名
        /// 
        public static object GetPropertyValue(this object obj, string propertyName)
        {
     
            return obj.GetType().GetProperty(propertyName, _bindingFlags).GetValue(obj);
        }

        /// 
        /// 设置某属性值
        /// 
        /// 对象
        /// 属性名
        /// 
        /// 
        public static void SetPropertyValue(this object obj, string propertyName, object value)
        {
     
            obj.GetType().GetProperty(propertyName, _bindingFlags).SetValue(obj, value);
        }

        /// 
        /// 是否拥有某字段
        /// 
        /// 对象
        /// 字段名
        /// 
        public static bool ContainsField(this object obj, string fieldName)
        {
     
            return obj.GetType().GetField(fieldName, _bindingFlags) != null;
        }

        /// 
        /// 获取某字段值
        /// 
        /// 对象
        /// 字段名
        /// 
        public static object GetGetFieldValue(this object obj, string fieldName)
        {
     
            return obj.GetType().GetField(fieldName, _bindingFlags).GetValue(obj);
        }

        /// 
        /// 设置某字段值
        /// 
        /// 对象
        /// 字段名
        /// 
        /// 
        public static void SetFieldValue(this object obj, string fieldName, object value)
        {
     
            obj.GetType().GetField(fieldName, _bindingFlags).SetValue(obj, value);
        }

        /// 
        /// 获取某字段值
        /// 
        /// 对象
        /// 方法名
        /// 
        public static MethodInfo GetMethod(this object obj, string methodName)
        {
     
            return obj.GetType().GetMethod(methodName, _bindingFlags);
        }

        /// 
        /// 改变实体类型
        /// 
        /// 对象
        /// 目标类型
        /// 
        public static object ChangeType(this object obj, Type targetType)
        {
     
            return obj.ToJson().ToObject(targetType);
        }

        /// 
        /// 改变实体类型
        /// 
        /// 目标泛型
        /// 对象
        /// 
        public static T ChangeType<T>(this object obj)
        {
     
            return obj.ToJson().ToObject<T>();
        }

        /// 
        /// 改变类型
        /// 
        /// 原对象
        /// 目标类型
        /// 
        public static object ChangeType_ByConvert(this object obj, Type targetType)
        {
     
            object resObj;
            if (targetType.IsGenericType && targetType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
     
                NullableConverter newNullableConverter = new NullableConverter(targetType);
                resObj = newNullableConverter.ConvertFrom(obj);
            }
            else
            {
     
                resObj = Convert.ChangeType(obj, targetType);
            }

            return resObj;
        }
    }
}

你可能感兴趣的:(#,C#类库/扩展方法,c#,asp.net,后端)