[英]How to copy value from class X to class Y with the same property name in c#?
假設我有兩個類:
public class Student
{
public int Id {get; set;}
public string Name {get; set;}
public IList<Course> Courses{ get; set;}
}
public class StudentDTO
{
public int Id {get; set;}
public string Name {get; set;}
public IList<CourseDTO> Courses{ get; set;}
}
我想將Student類中的值復制到StudentDTO類:
var student = new Student();
StudentDTO studentDTO = student;
我怎么能通過反思或其他解決方案來做到這一點?
列表使它變得棘手...我之前的回復(下面)僅適用於類似的屬性(不是列表)。 我懷疑你可能只需要編寫和維護代碼:
Student foo = new Student {
Id = 1,
Name = "a",
Courses = {
new Course { Key = 2},
new Course { Key = 3},
}
};
StudentDTO dto = new StudentDTO {
Id = foo.Id,
Name = foo.Name,
};
foreach (var course in foo.Courses) {
dto.Courses.Add(new CourseDTO {
Key = course.Key
});
}
編輯; 僅適用於淺拷貝 - 不是列表
反思是一種選擇,但速度很慢。 在3.5中,您可以使用Expression
將其構建為編譯的代碼。 Jon Skeet在MiscUtil中有一個預先推出的樣本 - 只需用作:
Student source = ...
StudentDTO item = PropertyCopy<StudentDTO>.CopyFrom(student);
因為它使用已編譯的Expression
所以它將大大超出反射。
如果您沒有3.5,則使用反射或ComponentModel。 如果您使用ComponentModel,您至少可以使用HyperDescriptor
來獲得它幾乎與Expression
一樣快
Student source = ...
StudentDTO item = new StudentDTO();
PropertyDescriptorCollection
sourceProps = TypeDescriptor.GetProperties(student),
destProps = TypeDescriptor.GetProperties(item),
foreach(PropertyDescriptor prop in sourceProps) {
PropertyDescriptor destProp = destProps[prop.Name];
if(destProp != null) destProp.SetValue(item, prop.GetValue(student));
}
好的,我只是查看了Marc發布的MiscUtil ,它非常棒。 我希望馬克不介意我在這里添加代碼。
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.ComponentModel;
using System.Linq.Expressions;
namespace ConsoleApplication1
{
class Program
{
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public IList<int> Courses { get; set; }
public static implicit operator Student(StudentDTO studentDTO)
{
return PropertyCopy<Student>.CopyFrom(studentDTO);
}
}
public class StudentDTO
{
public int Id { get; set; }
public string Name { get; set; }
public IList<int> Courses { get; set; }
public static implicit operator StudentDTO(Student student)
{
return PropertyCopy<StudentDTO>.CopyFrom(student);
}
}
static void Main(string[] args)
{
Student _student = new Student();
_student.Id = 1;
_student.Name = "Timmmmmmmmaaaahhhh";
_student.Courses = new List<int>();
_student.Courses.Add(101);
_student.Courses.Add(121);
StudentDTO itemT = _student;
Console.WriteLine(itemT.Id);
Console.WriteLine(itemT.Name);
Console.WriteLine(itemT.Courses.Count);
}
}
// COOLEST PIECE OF CODE FROM - http://www.yoda.arachsys.com/csharp/miscutil/
/// <summary>
/// Generic class which copies to its target type from a source
/// type specified in the Copy method. The types are specified
/// separately to take advantage of type inference on generic
/// method arguments.
/// </summary>
public class PropertyCopy<TTarget> where TTarget : class, new()
{
/// <summary>
/// Copies all readable properties from the source to a new instance
/// of TTarget.
/// </summary>
public static TTarget CopyFrom<TSource>(TSource source) where TSource : class
{
return PropertyCopier<TSource>.Copy(source);
}
/// <summary>
/// Static class to efficiently store the compiled delegate which can
/// do the copying. We need a bit of work to ensure that exceptions are
/// appropriately propagated, as the exception is generated at type initialization
/// time, but we wish it to be thrown as an ArgumentException.
/// </summary>
private static class PropertyCopier<TSource> where TSource : class
{
private static readonly Func<TSource, TTarget> copier;
private static readonly Exception initializationException;
internal static TTarget Copy(TSource source)
{
if (initializationException != null)
{
throw initializationException;
}
if (source == null)
{
throw new ArgumentNullException("source");
}
return copier(source);
}
static PropertyCopier()
{
try
{
copier = BuildCopier();
initializationException = null;
}
catch (Exception e)
{
copier = null;
initializationException = e;
}
}
private static Func<TSource, TTarget> BuildCopier()
{
ParameterExpression sourceParameter = Expression.Parameter(typeof(TSource), "source");
var bindings = new List<MemberBinding>();
foreach (PropertyInfo sourceProperty in typeof(TSource).GetProperties())
{
if (!sourceProperty.CanRead)
{
continue;
}
PropertyInfo targetProperty = typeof(TTarget).GetProperty(sourceProperty.Name);
if (targetProperty == null)
{
throw new ArgumentException("Property " + sourceProperty.Name + " is not present and accessible in " + typeof(TTarget).FullName);
}
if (!targetProperty.CanWrite)
{
throw new ArgumentException("Property " + sourceProperty.Name + " is not writable in " + typeof(TTarget).FullName);
}
if (!targetProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType))
{
throw new ArgumentException("Property " + sourceProperty.Name + " has an incompatible type in " + typeof(TTarget).FullName);
}
bindings.Add(Expression.Bind(targetProperty, Expression.Property(sourceParameter, sourceProperty)));
}
Expression initializer = Expression.MemberInit(Expression.New(typeof(TTarget)), bindings);
return Expression.Lambda<Func<TSource,TTarget>>(initializer, sourceParameter).Compile();
}
}
}
}
FYI
當我遇到同樣的問題時,我發現了AutoMapper( http://automapper.codeplex.com/ )然后在閱讀了AboutDev的答案后,我做了一些簡單的測試,結果令人印象深刻
這里的測試結果如下:
測試自動映射器:22322毫秒
測試隱式算子:310毫秒
測試屬性副本:250毫秒
測試發射映射器:281毫秒
我想強調它只是樣本(StudentDTO,Student)只有幾個屬性的樣本,但如果類有50-100個屬性會發生什么,我想它會顯着影響性能。
此處有更多測試詳細信息: .net中的對象復制方法:自動映射器,發射映射器,隱式操作,屬性復制
在任何類中編寫隱式運算符
public static implicit operator StudentDTO(Student student)
{
//use skeet's library
return PropertyCopy<StudentDTO>.CopyFrom(student);
}
現在你可以做到這一點
StudentDTO studentDTO = student;
有一個庫可以做到這一點 - http://emitmapper.codeplex.com/
它比AutoMapper快得多,它使用System.Reflection.Emit,因此代碼的運行速度幾乎和手寫的一樣快。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.