• 使用 Attribute +反射 来对两个类之间动态赋值


    看同事使用的 一个ORM 框架 中 有这样一个功能  通过特性(附加属性)的功能来 实现的两个类对象之间动态赋值的 功能  

    觉得这个功能不错,但是同事使用的 ORM 并不是我使用的  Dapper  所以就自己写了一个实现同样功能的 工具类出来。

    发个贴 为其他有这方面需求的人 来做个参考。 希望大家多提点意见。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Runtime.InteropServices;
    using System.Text;
    using System.Threading.Tasks;
    using System.Xml.Serialization;
    
    namespace ConsoleApplication2
    {
        class Program
        {
            static void Main(string[] args)
            {
                AnimalTypeTestClass testClass = new AnimalTypeTestClass() { Age = "1", Name = "2"};
                Na a = (Na)ClassToHellp.Map<Na>(testClass);
                Console.WriteLine(a.MyAge);
                Console.WriteLine(a.MyName);
            }
        }
        public class ClassToHellp
        {
            public static object Map<T>(object os) where T : class, new()
            {
                // 被转换的类
                var t = new T();
                var fieldInfos = t.GetType().GetFields();
                foreach (var mInfo in os.GetType().GetFields())
                {
                    var mInfoValue = mInfo.GetValue(os);
                    if (mInfoValue == null)
                        continue;
                    foreach (var field in Attribute.GetCustomAttributes(mInfo)
                        .Where(attr => attr.GetType() == typeof(ObjectToTypeAttribute))
                        .SelectMany(attr => fieldInfos.Where(field => field.Name == ((ObjectToTypeAttribute)attr).Field)))
                    {
                        field.SetValue(t, mInfoValue);
                    }
                }
                return t;
            }
    
        }
    
        [AttributeUsage(AttributeTargets.Field)]
        public class ObjectToTypeAttribute : Attribute
        {
            public string Field { get; set; }
            public ObjectToTypeAttribute(string pet)
            {
                Field = pet;
            }
        }
    
        public class AnimalTypeTestClass
        {
            [ObjectToType("MyName")]
            public string Name;
            [ObjectToType("MyAge")]
            public string Age;
    
        }
    
        public class Na
        {
            public string MyName;
    
            public string MyAge;
    
        }
    }

    请不要吐槽 使用反射 效率问题。 在不加载DLL 的前提下 反射的效率还是很高的。

    同样 在实体类只是对 字段经行筛选 判断 的LINQ 效率其实也还不错。

  • 相关阅读:
    关于cocos2dx之lua使用TableView
    设计模式-----工厂模式
    android YUV Sensor配置Camera应用的flash auto菜单
    AngularJS实现cookie跨域
    julia/pyplot 绘图加入标签和标题
    自己写unicode转换ascii码,wchar*到char*
    Android笔记——Activity中的数据传递案例(用户注冊)
    IIS预编译提升载入速度
    Python Tkinter 基础控件学习
    spfile
  • 原文地址:https://www.cnblogs.com/atliwen/p/4845948.html
Copyright © 2020-2023  润新知