-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathExpressionExtensions.cs
More file actions
65 lines (59 loc) · 2.49 KB
/
Copy pathExpressionExtensions.cs
File metadata and controls
65 lines (59 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using System.Linq.Expressions;
using System.Reflection;
namespace BytecodeApi.Extensions;
/// <summary>
/// Provides a set of <see langword="static" /> methods for interaction with <see cref="Expression" /> objects.
/// </summary>
public static class ExpressionExtensions
{
/// <summary>
/// Returns the member name of this <see cref="Expression{TDelegate}" />. If this instance does not resolve to a <see cref="MemberExpression" />, <see langword="null" /> is returned.
/// </summary>
/// <typeparam name="T">The member type.</typeparam>
/// <param name="member">The member to retrieve its name from.</param>
/// <returns>
/// The member name of this <see cref="Expression{TDelegate}" />, or <see langword="null" />, if this instance does not resolve to a <see cref="MemberExpression" />.
/// </returns>
public static string? GetMemberName<T>(this Expression<Func<T>> member)
{
Check.ArgumentNull(member);
return (member.Body as MemberExpression)?.Member.Name;
}
/// <summary>
/// Retrieves the value of the member of this <see cref="Expression{TDelegate}" />.
/// </summary>
/// <typeparam name="T">The member type.</typeparam>
/// <param name="member">The member to retrieve its value from.</param>
/// <returns>
/// The value of the member of this <see cref="Expression{TDelegate}" />.
/// </returns>
public static T GetMemberValue<T>(this Expression<Func<T>> member)
{
Check.ArgumentNull(member);
return (T)Expression.Lambda<Func<object>>(Expression.Convert((MemberExpression)member.Body, typeof(object))).Compile()();
}
/// <summary>
/// Sets the value of the member of this <see cref="Expression{TDelegate}" />.
/// </summary>
/// <typeparam name="T">The member type.</typeparam>
/// <param name="member">The member from which to update the value.</param>
/// <param name="obj">The class instance of <paramref name="member" />, or <see langword="null" />, if the member is <see langword="static" />.</param>
/// <param name="value">The new value to be assigned to <paramref name="member" />.</param>
public static void SetMemberValue<T>(this Expression<Func<T>> member, object obj, T value)
{
Check.ArgumentNull(member);
MemberInfo? memberInfo = (member.Body as MemberExpression)?.Member;
if (memberInfo is PropertyInfo property)
{
property.SetValue(obj, value);
}
else if (memberInfo is FieldInfo field)
{
field.SetValue(obj, value);
}
else
{
throw Throw.UnsupportedType(nameof(member));
}
}
}