Get Private Member Func <T> with reflection

I have a class with a private member definition like this:

[MyCustomAttribute] private Func<String, String> MyFuncMember = (val) => val + " World! "; 

and I'm trying to get the attribute that I put on it. Now I tried with Type.GetMembers() , Type.GetFields() and Type.GetMethods using the corresponding BindingFlags ( BindingFlags.NonPublic ) and I just can't get this member. How can i get it? Could it be a problem if the class where it is defined is the class sealed ?

Thanks in advance for your answers.

+4
source share
2 answers

Try using this as anchor flags:

 BindingFlags.NonPublic | BindingFlags.Instance 

Without the BindingFlags.Instance flag BindingFlags.Instance it cannot find your instance field.

In general, when you use Type.GetField , you need to install:

  • one (or both) of BindingFlags.Instance and BindingFlags.Static

    and

  • one (or both) of BindingFlags.Public and BindingFlags.NonPublic .

Operator | Combines flags using a binary code or operation, which means both flags are checked.

+3
source
 typeof(YourType) .GetMember("MyFuncMember", BindingFlags.Instance | BindingFlags.NonPublic) .GetCustomAttributes(true); 
+1
source

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


All Articles