Simple syntax for getting type member in extension method (C #)

I am trying to write an extension method that will give me MemberInforepresenting an element of a given type using lambda expressions. Ideally, I would like to write

var info = MyType.GetMember(m => m.MyProperty);

or also acceptable

var info = typeof(MyType).GetMember(m => m.MyProperty);

or even

var info = typeof(MyType).GetMember((MyType m) => m.MyProperty);

I have a common method signature that works, but I need to specify all the type parameters, and I would really like C # to output them. As far as I can tell, if I just find the right way to indicate the signature of the extension method, there should be enough information (at least the last of) pieces of code to output everything, but, according to the compiler, there is "t.

, - , . ,

public static MemberInfo GetMember<TType, TReturnType>(static TType, Expression<Func<TType, TReturnType>> member)

. , , , , ,

public static MemberInfo GetMember<TType, TReturnType>(this Type t, Expression<Func<TType, TReturnType>> member)

, .

+3
2

:

public static MemberInfo GetMember<TType, TReturnType>
    (this TType ignored,
     Expression<Func<TType, TReturnType>> expression)

:

default(MyType).GetMember(m => m.MyProperty)

, default(MyType) - MyType, .

+2

, , , , :

public static MemberInfo GetMember<TType, TReturnType>(Expression<Func<TType, ReturnType>> member)

:

MemberInfo info = YourClass.GetMember((YourConcreteType instance) => instance.Property);

, , , :

public static MemberInfo GetMember<TType, TReturnType>(this TType instance, Expression<Func<TType, ReturnType>> member)

:

MemberInfo info = yourInstanceOfTType.GetMember(instance => instance.Property);
0

Source: https://habr.com/ru/post/1756321/


All Articles