zoukankan      html  css  js  c++  java
  • C# 通过反射为一个对象赋值

    /// <summary>
       /// 反射赋值
       /// </summary>
       public 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);
                   }
               }
           }
       }
    用法  ObjectReflection.AutoMapping(model, vmModel);

    这里将model属性的值赋值给了具体相同属性名称的vmModel。

    代码改变世界
  • 相关阅读:
    git 实践(二) push的使用
    git 实践(一) pull的使用
    redux项目实战应用笔录
    浅谈ES6的Object.assign()浅拷贝
    React下reducer中处理数组&&对象的赋值改动
    git pull与git clone
    (0)网络编程基础(网络基本知识)
    (1)什么是socket(套接字)
    (12)异常处理
    (11)类的内置函数
  • 原文地址:https://www.cnblogs.com/oreobyzf/p/6244366.html
Copyright © 2011-2022 走看看