简体   繁体   中英

Using reflection to call a static method on a generic class

I have a generic class with a non generic static method that performs some operations on the type in question.

class MyClass<T> {  
  static List<T> _listOfStuff;

  public static void DoX() { _listOfStuff.Clear(); }
}

Rather than writing the code below, I'd like to use reflection and loop over the generic types and calling DoX().

Keep in mind that the list of types could grow in the future and that MyClass could be used by developers external to the assembly where this code is maintained. I need an automated way to get a Type[] array of int , string , TypeX .

MyClass<int>.DoX();
MyClass<string>.DoX();
MyClass<TypeX>.DoX();

Any help would be appreciated.

It seems to me that this is a very weird thing to do. If you want to perform some cleanup, you might consider using non-static classes, or something else. Again, this really does smell of bad design to me, but I can't advise you any better way, because I still have no idea why are you trying to do this.

If you're sure you want to do this, there doesn't seem to be a way to get a list of all used types directly. But you can keep a list of all used constructed types in some other non-generic type and add to it from the static constructor.

But if all you want to do is to call DoX() for all types, you don't actually need a list of types, you can use a list of delegates to DoX() for all used types. That could look something like this:

class MyClass<T>
{
    static MyClass()
    {
        MyClass.DoXDelegates.Add(DoX);
    }

    public static void DoX() { /* whatever */ }
}

static class MyClass
{
    private static readonly List<Action> s_DoXDelegates = new List<Action>();
    internal static List<Action> DoXDelegates
    {
        get { return s_DoXDelegates; }
    }

    internal static void DoXForAll()
    {
        foreach (var doXDelegate in DoXDelegates)
            doXDelegate();
    }
}

Assuming if you've just got a static list of the types (warning - not compile checked):

Type[] types = new[] { typeof(int), typeof(string), typeof(TypeX) }:

Type myClass = typeof(MyClass<>);

foreach (Type t in types) {
    Type genMyClass = myClass.MakeGenericType(t);
    genMyClass.InvokeMember("DoX", BindingFlags.Public | BindingFlags.Static, null, null, null);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM