如何以编程方式轻松检查当前程序集是否是以调试模式或发布模式编译的?
如何以编程方式轻松检查当前程序集是否是以调试模式或发布模式编译的?
bool isDebugMode = false;
#if DEBUG
isDebugMode = true;
#endif
如果你想在调试版和发布版之间编写不同的代码行为,应该按照以下方式进行:
#if DEBUG
int[] data = new int[] {1, 2, 3, 4};
#else
int[] data = GetInputData();
#endif
int sum = data[0];
for (int i= 1; i < data.Length; i++)
{
sum += data[i];
}
或者,如果你想在调试版本的函数上执行某些检查,你可以像这样做:
public int Sum(int[] data)
{
Debug.Assert(data.Length > 0);
int sum = data[0];
for (int i= 1; i < data.Length; i++)
{
sum += data[i];
}
return sum;
}
Debug.Assert
不会在发布版本中包含。
我希望这对你有用:
public static bool IsRelease(Assembly assembly) {
object[] attributes = assembly.GetCustomAttributes(typeof(DebuggableAttribute), true);
if (attributes == null || attributes.Length == 0)
return true;
var d = (DebuggableAttribute)attributes[0];
if ((d.DebuggingFlags & DebuggableAttribute.DebuggingModes.Default) == DebuggableAttribute.DebuggingModes.None)
return true;
return false;
}
public static bool IsDebug(Assembly assembly) {
object[] attributes = assembly.GetCustomAttributes(typeof(DebuggableAttribute), true);
if (attributes == null || attributes.Length == 0)
return true;
var d = (DebuggableAttribute)attributes[0];
if (d.IsJITTrackingEnabled) return true;
return false;
}
If System.Diagnostics.Debugger.IsAttached Then DoSomething '(例如让一个窗体表现不同)
。 - Neil Dunlop