Skip to content

Commit f3df57c

Browse files
committed
add reflection set value feature
1 parent b985a35 commit f3df57c

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

src/Mapster/Adapters/ClassAdapter.cs

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,18 @@ protected override Expression CreateBlockExpression(Expression source, Expressio
129129
}
130130
else
131131
{
132-
adapt = member.DestinationMember.SetExpression(destination, adapt);
132+
//Todo Try catch block should be removed after pull request approved
133+
try
134+
{
135+
var destinationPropertyInfo = (PropertyInfo)member.DestinationMember.Info!;
136+
adapt = destinationPropertyInfo.IsInitOnly()
137+
? SetValueByReflection(destination, (MemberExpression)adapt, arg.DestinationType)
138+
: member.DestinationMember.SetExpression(destination, adapt);
139+
}
140+
catch (Exception e)
141+
{
142+
adapt = member.DestinationMember.SetExpression(destination, adapt);
143+
}
133144
}
134145
}
135146
else if (!adapt.IsComplex())
@@ -146,6 +157,7 @@ protected override Expression CreateBlockExpression(Expression source, Expressio
146157
tuple = Tuple.Create(new List<Expression>(), body);
147158
conditions[member.Ignore.Condition] = tuple;
148159
}
160+
149161
tuple.Item1.Add(adapt);
150162
}
151163
else
@@ -166,6 +178,21 @@ protected override Expression CreateBlockExpression(Expression source, Expressio
166178
return lines.Count > 0 ? (Expression)Expression.Block(lines) : Expression.Empty();
167179
}
168180

181+
private static Expression SetValueByReflection(Expression destination, MemberExpression adapt,
182+
Type destinationType)
183+
{
184+
var memberName = adapt.Member.Name;
185+
var typeofExpression = Expression.Constant(destinationType);
186+
var getPropertyMethod = typeof(Type).GetMethod("GetProperty", new[] { typeof(string) })!;
187+
var getPropertyExpression = Expression.Call(typeofExpression, getPropertyMethod,
188+
Expression.Constant(memberName));
189+
var setValueMethod =
190+
typeof(PropertyInfo).GetMethod("SetValue", new[] { typeof(object), typeof(object) })!;
191+
var memberAsObject = adapt.To(typeof(object));
192+
return Expression.Call(getPropertyExpression, setValueMethod,
193+
new[] { destination, memberAsObject });
194+
}
195+
169196
protected override Expression? CreateInlineExpression(Expression source, CompileArgument arg)
170197
{
171198
//new TDestination {

0 commit comments

Comments
 (0)