ReflectorMemberOfT(ExpressionFuncT) Method
Gets the returned member of an expression providing a refactoring-safe way for
referencing a field, property, constructor or function method.
Namespace: KGySoft.ReflectionAssembly: KGySoft.CoreLibraries (in KGySoft.CoreLibraries.dll) Version: 8.1.0
public static MemberInfo MemberOf<T>(
Expression<Func<T>> expression
)
Public Shared Function MemberOf(Of T) (
expression As Expression(Of Func(Of T))
) As MemberInfo
public:
generic<typename T>
static MemberInfo^ MemberOf(
Expression<Func<T>^>^ expression
)
static member MemberOf :
expression : Expression<Func<'T>> -> MemberInfo
- expression ExpressionFuncT
- An expression returning a member.
- T
- Type of the returned member in the expression.
MemberInfoA
MemberInfo instance that represents the returned member of the
expression Similarly to the typeof operator, which provides a refactoring-safe reference to a Type,
this method provides a non-string access to a field, property, constructor or function method:
MemberInfo ctorList = Reflector.MemberOf(() => new List<int>()); // ConstructorInfo: List<int>().ctor()
MemberInfo methodIndexOf = Reflector.MemberOf(() => default(List<int>).IndexOf(default(int))); // MethodInfo: List<int>.IndexOf(int) - works without a reference to a List
MemberInfo fieldEmpty = Reflector.MemberOf(() => string.Empty); // FieldInfo: String.Empty
MemberInfo propertyLength = Reflector.MemberOf(() => default(string).Length); // PropertyInfo: String.Length - works without a reference to a string
Constant fields cannot be reflected by this method because the C# compiler emits the value of the constant into
the expression instead of the access of the constant field.
To reflect an action method, you can use the MemberOf(ExpressionAction) method.
To reflect methods, you can actually cast the method to a delegate and get its Method property:
MemberInfo methodIndexOf = ((Action<int>)new List<int>().IndexOf).Method; // MethodInfo: List<int>.IndexOf(int) - a reference to a List is required
Accessing a method by the delegate cast is usually faster than using this method. However, you must have an instance to
access instance methods. That means that you cannot use the default operator for reference types
to access their instance methods. If the constructor of such a type is slow, then using this method can be
more effective to access an instance method.