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

时间:2015-02-12 11:20:53

标签: c# appdomain system.reflection

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

  1. 获取所有以单词" static"结尾的汇编。从一个 应用域
  2. 获取静态类,该类以单词" cache"结束。 来自步骤1检索的程序集
  3. 执行一个名为"的静态方法"来自全班 从第2步检索

1 个答案:

答案 0 :(得分: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);