ARTICLE AD BOX
What's going on here is that both the base and the derived class implement the interface using Explicit Interface Implementation, so those methods are actually private methods which implement the interface.
The base implementation of the interface has been overridden, but the private methods are still accessible using reflection. Note that as far as normal C# is concerned, these methods do not exist anymore on this object, only the derived class's methods exist.
You need to recursively get all base class Type objects, then get the implementation mapping from them to find which private methods you want to call. In the case of a property access you need to find its GetMethod.
[Fact] public async Task Test1() { var obj = new DerivedClass(); var types = GetAllTypes(obj.GetType()); var values = types .SelectMany(t => t.GetInterfaces() .Where(i => i.GetGenericTypeDefinition() == typeof(A<>)) .Select(i => { var interfaceMap = t.GetInterfaceMap(i); var interfaceMethod = i.GetProperty(nameof(A<>.Property)).GetMethod; var targetMethod = interfaceMap.TargetMethods[interfaceMap.InterfaceMethods.IndexOf(interfaceMethod)]; return targetMethod.Invoke(obj, null)!; }) ); Assert.Equal(4, values.Count()); } private IEnumerable<Type> GetAllTypes(Type type) { while (type is not null && type != typeof(object)) { yield return type; type = type.BaseType; } }On the other hand, I'm not really sure what this "Test" is supposed to achieve. All we really get from here is "how many times was the interface implemented".
78.6k8 gold badges35 silver badges77 bronze badges
Explore related questions
See similar questions with these tags.
