65.9K
CodeProject 正在变化。 阅读更多。
Home

C# 中的简单模型/实体映射器

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.33/5 (2投票s)

2015 年 3 月 12 日

CPOL
viewsIcon

18321

这是“C# 中的简单模型/实体映射器”的替代方案

引言

原始文章是 https://codeproject.org.cn/Tips/807820/Simple-Model-Entity-mapper-in-Csharp

原始文章

引用

引言

在使用 C# 时,我们可能希望将一个模型/实体映射到另一个模型/实体。 反射是可以在此时帮助我们的关键。

所以让我们看看如何使用反射在 C# 中创建一个简单的模型或实体映射器。

引用

背景

假设我们有一些模型,例如

IStudent 接口

interface IStudent
{
    long Id { get; set; }
    string Name { get; set; }
}

Student 类

class Student : IStudent
{
    public long Id { get; set; }
    public string Name { get; set; }
}

StudentLog 类

class StudentLog : IStudent
{
    public long LogId { get; set; }
    public long Id { get; set; }
    public string Name { get; set; }
}

其中 Student StudentLog 都具有一些公共属性(名称和类型相同)。

几年前,我编写了几乎相同的代码,但我们还没有 4.0 Framework。 我的代码非常糟糕且丑陋,所以在发布到这个网站之前,我做了一些更改。

我认为我的版本更快,因为我使用了一个较少的 foreach

Using the Code

public static TTarget MapTo<TSource, TTarget>(TSource aSource) where TTarget : new()
{
    const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic;

    TTarget aTarget = new TTarget();
    Hashtable sourceData = new Hashtable();
    foreach (PropertyInfo pi in aSource.GetType().GetProperties(flags))
    {                
        if (pi.CanRead)
        {
            sourceData.Add(pi.Name, pi.GetValue(aSource, null));
        }
    }

    foreach (PropertyInfo pi in aTarget.GetType().GetProperties(flags))
    {   
//fix from rvaquette           
        if (pi.CanWrite)
        {
            if(sourceData.ContainsKey(pi.Name))
            {
                pi.SetValue(aTarget, sourceData[pi.Name], null);
            }
        }
    }
    return aTarget;
}
Student source = new Student() { Id = 1, Name = "Smith" };
StudentLog target = MapTo<Student, StudentLog>(source);
© . All rights reserved.