簡體   English   中英

如何從應用程序域中所有已加載的程序集中獲取所有靜態類,以及如何使用反射調用靜態方法

[英]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. 從步驟1檢索的程序集中獲取以單詞“ cache”結尾的靜態類
  3. 從步驟2檢索的類中執行名為“ invalidate”的靜態方法

嘗試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM