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

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

我的要求是这样的,可以吗?如果是,有人可以指点我这方面的任何资源吗?

  1. 获取所有以单词"static"结尾的程序集 应用域
  2. 获取以单词 "cache" 结尾的静态 class 来自步骤 1 中检索到的程序集
  3. 从 class 执行名为 "invalidate" 的静态方法 从第 2 步检索

试试这个:

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);
            }
        }
    }
}

或者...如果您更喜欢 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);