Let’s say that I have the following delegate:
public delegate void Example();
and a class such as the following:
public class TestClass { Example FailingTest = () => Assert.Equal(0,1); }
How can I use reflection to get the name ‘FailingTest’?
So far I have tried:
var possibleFields = typeof(TestClass).GetFields(relevant_binding_flags) .Where(x => x.FieldType.Equals(typeof(Example))); foreach(FieldInfo oneField in possibleFields) { // HERE I am able to access the declaring type name var className = oneField.ReflectedType.Name; // == 'TestClass' // but I am not able to access the field // name 'FailingTest' because: var fieldName = oneField.Name; // == 'CS$<>9__CachedAnonymousMethodDelegate1' }
Stepping through in the debugger, I am unable to find a path to the name of the declared field, ‘FailingTest’.
Is that info retained at runtime or is it lost when the anonymous delegate is assigned?
What
BindingFlagsare you passing toGetFields? I used these:and I was able to see the name of the field.