12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Reflection;
- using System.Text;
- using System.Threading.Tasks;
- namespace NXWMS.Code.Reflections
- {
- // <summary>
- /// 反射赋值
- /// </summary>
- public static class ObjectReflection
- {
- public static PropertyInfo[] GetPropertyInfos(Type type)
- {
- return type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
- }
- /// <summary>
- /// 实体属性反射
- /// </summary>
- /// <typeparam name="S">赋值对象</typeparam>
- /// <typeparam name="T">被赋值对象</typeparam>
- /// <param name="s"></param>
- /// <param name="t"></param>
- public static void AutoMapping<S, T>(S s, T t)
- {
- PropertyInfo[] pps = GetPropertyInfos(s.GetType());
- Type target = t.GetType();
- foreach (var pp in pps)
- {
- PropertyInfo targetPP = target.GetProperty(pp.Name);
- object value = pp.GetValue(s, null);
- if (targetPP != null && value != null)
- {
- targetPP.SetValue(t, value, null);
- }
- }
- }
- /// <summary>
- /// 设置类中属性
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="t"></param>
- /// <param name="fieldName"></param>
- /// <param name="value"></param>
- /// <returns></returns>
- public static string SetFieldValue<T>(T t,string fieldName,object value) where T: class
- {
- try
- {
- var type = t.GetType();
- var propertyInfo = type.GetProperty(fieldName);
- propertyInfo.SetValue(t, value, null);
- return string.Empty;
- }
- catch(Exception ex)
- {
- return ex.Message;
- }
- }
- /// <summary>
- /// 获取类中属性
- /// </summary>
- /// <param name="FieldName"></param>
- /// <param name="obj"></param>
- /// <returns></returns>
- public static string GetFieldValue<T>(T t,string FieldName) where T : class
- {
- try
- {
- Type Ts = t.GetType();
- object o = Ts.GetProperty(FieldName).GetValue(t, null);
- string Value = Convert.ToString(o);
- if (string.IsNullOrEmpty(Value)) return null;
- return Value;
- }
- catch
- {
- return null;
- }
- }
- }
- }
|