1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- /* ==============================================================================
- * 功能描述:ObjectExtend
- * 创 建 者:Garrett
- * 创建日期:2017/10/16 16:55:19
- * ==============================================================================*/
- using System;
- using System.ComponentModel;
- using System.Reflection;
- namespace SAGA.DotNetUtils.Extend
- {
- /// <summary>
- /// ObjectExtend
- /// </summary>
- public static class ObjectExtend
- {
- /// <summary>
- /// 转为String
- /// </summary>
- /// <param name="obj"></param>
- /// <returns></returns>
- public static string ToStr(this object obj)
- {
- string result = "";
- if (obj != null)
- {
- try
- {
- result = Convert.ToString(obj);
- }
- catch (Exception e)
- {
- }
-
- }
- return result;
- }
- public static bool IsNullOrEmpty(this object obj)
- {
- return obj==null||((string) obj)=="";
- }
- public static bool IsNotNullEmpty(this object obj)
- {
- return !obj.IsNullOrEmpty();
- }
- /// <summary>
- /// 通过反射对有DescriptionAttribute标记的属性进行赋值
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="mode"></param>
- /// <param name="values"></param>
- /// <param name="func"></param>
- /// <returns></returns>
- public static void ReflectSetPropertyValue<T>(this T mode, object values, Func<object, string, string> func)
- {
- foreach (PropertyInfo property in mode.GetType().GetProperties())
- {
- var description = property.GetCustomAttribute<DescriptionAttribute>()?.Description;
- string value = "";
- try
- {
- value = func.Invoke(values,description);
- }
- catch (Exception e)
- {
- }
- if (value.IsNotNullEmpty())
- {
- object obj = Convert.ChangeType(value, property.PropertyType);
- property.SetValue(mode, obj);
- }
- }
- }
- }
- }
|