ASP.NET C# 如何将源 Id 映射到目标对象
创始人
2024-09-14 10:01:30
0

在ASP.NET C#中,可以使用反射来将源对象的属性映射到目标对象。下面是一个示例代码:

using System;
using System.Reflection;

public class SourceObject
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

public class TargetObject
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public static class Mapper
{
    public static void MapProperties(object source, object target)
    {
        Type sourceType = source.GetType();
        Type targetType = target.GetType();

        PropertyInfo[] sourceProperties = sourceType.GetProperties();
        PropertyInfo[] targetProperties = targetType.GetProperties();

        foreach (PropertyInfo sourceProperty in sourceProperties)
        {
            PropertyInfo targetProperty = Array.Find(targetProperties, p => p.Name == sourceProperty.Name);

            if (targetProperty != null && targetProperty.PropertyType == sourceProperty.PropertyType)
            {
                object value = sourceProperty.GetValue(source);
                targetProperty.SetValue(target, value);
            }
        }
    }
}

public class Program
{
    public static void Main()
    {
        SourceObject source = new SourceObject()
        {
            Id = 1,
            Name = "Test",
            Description = "Sample description"
        };

        TargetObject target = new TargetObject();

        Mapper.MapProperties(source, target);

        Console.WriteLine("Id: " + target.Id);
        Console.WriteLine("Name: " + target.Name);
    }
}

在上面的示例中,SourceObject是源对象,TargetObject是目标对象。Mapper类中的MapProperties方法使用反射来将源对象的属性映射到目标对象。在Main方法中,创建了一个源对象和一个目标对象,并使用MapProperties方法将源对象的属性映射到目标对象。最后打印目标对象的属性值。

注意,这只是一个简单的示例,实际应用中可能需要处理更复杂的映射逻辑和异常情况。

相关内容

热门资讯

7分钟普及!微信小程序广丰51... 自定义微信小程序系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专用辅助器,不管你是想...
1分钟普及!爱玩辽宁麻将能赢,... 您好,友乐这款游戏可以开挂的,确实是有挂的,需要了解加微【485275054】很多玩家在这款游戏中打...
信息共享!wepoke游戏辅助... 信息共享!wepoke游戏辅助工具,德扑之星破解其实真的有挂,微扑克教程(有挂教程)-哔哩哔哩相信很...
1分钟实锤!浙江游戏大厅插件,... 1分钟实锤!浙江游戏大厅插件,福建天天开心辅助器真的假的,必赢方法(真的有挂)1、浙江游戏大厅系统规...
1分钟了解!微扑克发牌算法,W... 1分钟了解!微扑克发牌算法,Wepoke德州原来是真的有挂,德州教程(有挂详情)-哔哩哔哩;《WPK...
四分钟了解!浙东纸牌有挂(透视... 四分钟了解!浙东纸牌有挂(透视)外挂透视辅助器安装(2022已更新)(哔哩哔哩)是一款可以让一直输的...
热点推荐!wpk数据手机软件叫... 热点推荐!wpk数据手机软件叫啥,wpk网页版原来是真的有挂,安装教程(有挂技巧)-哔哩哔哩;(需添...
7分钟攻略!潮汕雀友会有猫腻,... 您好,潮汕雀友会这款游戏可以开挂的,确实是有挂的,需要了解加微【485275054】很多玩家在这款游...
7分钟了解!德扑之星刷数据(W... 【福星临门,好运相随】;7分钟了解!德扑之星刷数据(WPK打法)外挂透明挂辅助脚本(透视)揭秘教程(...
七分钟科普!徐州66麻将秘籍,... 七分钟科普!徐州66麻将秘籍,雀神辅助器免费版苹果手机,安装教程(有挂功能);辅助插件是一个在免局卡...