在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
方法将源对象的属性映射到目标对象。最后打印目标对象的属性值。
注意,这只是一个简单的示例,实际应用中可能需要处理更复杂的映射逻辑和异常情况。