您的位置:首页 > 其它

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

2015-09-29 11:50 288 查看
看同事使用的 一个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 效率其实也还不错。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: