简体   繁体   English

如何从应用程序域中所有已加载的程序集中获取所有静态类,以及如何使用反射调用静态方法

[英]How to get all the static classes from all the loaded assemblies in an app-domain and invoke a static method using reflection

my requirement is as follows, is this possible ? 我的要求如下,这可能吗? if yes can someone please point me to any resources on this ? 如果是的话,有人可以指出我的任何资源吗?

  1. get all the assemblies which end with the word "static" from an app domain 从应用程序域中获取所有以单词“ static”结尾的程序集
  2. get hold of the static class which ends with the word "cache" from the assembly retrieved from step 1 从步骤1检索的程序集中获取以单词“ cache”结尾的静态类
  3. Execute a static method named "invalidate" from the class retrieved from step 2 从步骤2检索的类中执行名为“ invalidate”的静态方法

Try this: 尝试这个:

foreach(Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
{
    if (asm.GetName().Name.EndsWith("static"))
    {
        foreach(Type type in asm.GetTypes())
        {
            if (type.Name.EndsWith("cache"))
            {
                MethodInfo method = type.GetMethod("invalidate", BindingFlags.Static | BindingFlags.Public, null, Type.EmptyTypes, null);
                if (method != null)
                    method.Invoke(null, null);
            }
        }
    }
}

Or... if you prefer LINQ: 或者...如果您更喜欢LINQ:

foreach(MethodInfo method in 
    AppDomain.CurrentDomain
    .GetAssemblies().Where(asm => asm.GetName().Name.EndsWith("static"))
    .SelectMany(asm => asm.GetTypes().Where(type => type.Name.EndsWith("cache"))
    .Select(type => type.GetMethod("invalidate", BindingFlags.Static | BindingFlags.Public, null, Type.EmptyTypes, null)).Where(method => method != null)))
        method.Invoke(null, null);

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

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