简体   繁体   English

使用反射在泛型类上调用静态方法

[英]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(). 与其编写下面的代码,不如使用反射和遍历泛型类型并调用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. 请记住,类型列表可能会在将来增长,并且MyClass可能会被维护该代码的程序集外部的开发人员使用。 I need an automated way to get a Type[] array of int , string , TypeX . 我需要一种自动化的方法来获取intstringTypeXType[]数组。

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. 但是,如果您要做的只是为所有类型调用DoX() ,则实际上不需要类型列表, DoX()以为所有使用的类型使用一个代表DoX()的委托列表。 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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