Last active
February 26, 2025 11:05
-
-
Save tqk2811/063e9856d79a46090d37e9c442352194 to your computer and use it in GitHub Desktop.
CopyProperties between same object type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void CopyTo<T, TProperties>(this T source, T target, Expression<Func<T, TProperties>> expression) | |
{ | |
MemberExpression? memberExpression = expression.Body as MemberExpression; | |
if (memberExpression is null) | |
return; | |
List<MemberExpression> listMemberExpression = new([memberExpression]);//child to parent | |
while (true) | |
{ | |
MemberExpression? child_memberExpression = memberExpression?.Expression as MemberExpression; | |
if (child_memberExpression is null) | |
{ | |
break; | |
} | |
else | |
{ | |
memberExpression = child_memberExpression; | |
listMemberExpression.Add(child_memberExpression); | |
} | |
} | |
listMemberExpression.Reverse(); | |
object? _target = target; | |
foreach (MemberExpression member in listMemberExpression) | |
{ | |
PropertyInfo? propertyInfo = member?.Member as PropertyInfo; | |
if (propertyInfo is not null) | |
{ | |
if (listMemberExpression.Last().Equals(member)) | |
{ | |
if (propertyInfo.CanRead && propertyInfo.CanWrite) | |
{ | |
var compile = expression.Compile(); | |
var value = compile(source); | |
propertyInfo.SetValue(_target, value); | |
} | |
break; | |
} | |
else if (propertyInfo.CanRead) | |
{ | |
_target = propertyInfo.GetValue(_target); | |
} | |
else break; | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Data a = new(); | |
Data b = new(); | |
a.CopyTo(b,x=> x.Prop1); | |
a.CopyTo(b,x=> x.Prop2.Child1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment