mercredi 25 juillet 2018

Call a public method of a object's actual type

Consider following code

using System.Reflection;
public class Sample { 
    private class User { 
        public string Name; 
    } 
    private List<User> Users = new List<User> { 
        new User() { Name = "Alice" }, 
        new User() { Name = "Bob" } 
    }; 
}
var sample = new Sample();
var usersOfSample = typeof(Sample).GetField("Users", BindingFlags.Instance | 
    BindingFlags.NonPublic).GetValue(sample);

With reflection, I can get the value of Users, while it is a List of a private class. Now I want to call List.Clear() on users.
My first idea is convert it into dynamic. However, following code does not work as my expectation.

dynamic usersOfSampleDyn = (usersOfSample as dynamic);
usersOfSampleDyn.Clear();

It throws a RuntimeBinderException. Later I try this code in C# Interactive, it says 'object' does not contain a definition for 'Clear'.
Using reflection to call this method works, as following

usersOfSample.GetType().GetMethod("Clear").Invoke(usersOfSample, new object[0]);

Here is my question:
1. Why I can't call Clear() when cast usersOfSample into dynamic?
1.1 Is usersOfSampleDyn a dynamic { List<T> } or a dynamic { object { List<T> } }?
1.2 If usersOfSampleDyn is dynamic { object { List<T> } }, how to convert it into dynamic { List<T> }?
2. What's the correct way to call a public List method on object { List<InaccessibleClass> }?





Aucun commentaire:

Enregistrer un commentaire