당신은 같은 우는 소리, 자신의 확장 방법을 쓸 수 있습니다 사용하고 읽어
public static class ExtendedClassPropMapping
{
public static Y MapTo<Y>(this object input) where Y : class, new()
{
Y output = new Y();
var propsT = input.GetType().GetProperties();
var propsY = typeof(Y).GetProperties();
var similarsT = propsT.Where(x =>
propsY.Any(y => y.Name == x.Name
&& y.PropertyType == x.PropertyType)).OrderBy(x => x.Name).ToList();
var similarsY = propsY.Where(x =>
propsT.Any(y => y.Name == x.Name
&& y.PropertyType == x.PropertyType)).OrderBy(x => x.Name).ToList();
for (int i = 0; i < similarsY.Count; i++)
{
similarsY[i]
.SetValue(output, similarsT[i].GetValue(input, null), null);
}
return output;
}
public static T MapNew<T>(this T input) where T : class, new()
{
T output = new T();
var similarsT = input.GetType().GetProperties().OrderBy(x => x.Name).ToList();
var similarsY = output.GetType().GetProperties().OrderBy(x => x.Name).ToList();
for (int i = 0; i < similarsY.Count; i++)
{
similarsY[i]
.SetValue(output, similarsT[i].GetValue(input, null), null);
}
return output;
}
}
는 그런 다음과 같이 사용할 수 있습니다 :
,
public Teacher ConvertInterfaceToClass(ITeacher teacher)
{
return teacher.MapTo<Teacher>();
}
public void CopyTeacher(Teacher source, out Teacher destination)
{
destination = source.MapTo<Teacher>();
}
공용 인터페이스를 공유하지 않는 한 3 가지 옵션, 1) 한 번에 한 줄의 세 가지 옵션이 있습니다. 2) Automapper (사용하기 쉽고 매우 유연함)와 같은 도구를 사용하십시오. 3) reflection을 사용하십시오. –
@ Gary.S 동일한 인터페이스를 구현한다면 무엇이 바뀔까요? 내가 본 것처럼, 당신은 여전히 똑같은 3 가지 옵션을가집니다. –
그들이 동일한 인터페이스를 구현하는 경우 구체적인 구현보다는 주변 인터페이스를 사용할 수 있습니다. 필요한 속성을 사용하여 의존 할 수있는 경우 매핑 할 필요가 없습니다. –