2010-10-07 62 views
5

我有一個引用的庫,在那裏我想要執行一個不同的操作,如果引用它的程序集處於DEBUG/RELEASE模式。如何判斷調用程序集是否處於DEBUG模式編譯參考庫

是否可以打開調用程序集處於DEBUG/RELEASE模式的條件?

有沒有辦法做到這一點,而不訴諸類似:

bool debug = false; 

#if DEBUG 
debug = true; 
#endif 

referencedlib.someclass.debug = debug; 

的參考組件將始終是應用程序的起點(即Web應用程序

回答

8

Google says這是很簡單的你得到的問題從組件的DebuggableAttribute信息:

IsAssemblyDebugBuild(Assembly.GetCallingAssembly()); 

private bool IsAssemblyDebugBuild(Assembly assembly) 
{ 
    foreach (var attribute in assembly.GetCustomAttributes(false)) 
    { 
     var debuggableAttribute = attribute as DebuggableAttribute; 
     if(debuggableAttribute != null) 
     { 
      return debuggableAttribute.IsJITTrackingEnabled; 
     } 
    } 
    return false; 
} 
+0

對不起,雖然是一個痛苦,但「谷歌」不說什麼。這是我的一些例子,因爲我是一個懶惰的工具。 :D – Nayan 2010-10-07 10:02:32

+1

我不太懶!我似乎今天有弱谷歌:( – 2010-10-07 10:16:55

+0

@Nayan谷歌說不! – bitbonk 2010-10-07 10:48:00

1

您可以使用reflection來獲取調用程序集並使用this method來檢查它是否處於調試模式。

0

接受的答案是正確的。這是一個跳過迭代階段並作爲擴展方法提供的替代版本:

public static class AssemblyExtensions 
{ 
    public static bool IsDebugBuild(this Assembly assembly) 
    { 
     if (assembly == null) 
     { 
      throw new ArgumentNullException(nameof(assembly)); 
     } 

     return assembly.GetCustomAttribute<DebuggableAttribute>()?.IsJITTrackingEnabled ?? false; 
    } 
} 
相關問題