2009-03-17 14 views

答えて

97
Boolean 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はリリースビルドに含まれません。

+0

は、JIT最適化されたビルドについて尋ねOPですか?もしそうなら、この答えは間違っています。デバッグ属性は、JIT最適化ビルドで宣言することも、最適化しないこともできます。 –

11

私はこれがあなたのために役立つことを願って:

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; 
} 
+4

両方の関数に次の行がある理由: if(attributes == null || attributes.Length == 0) trueを返します。 このコードで何か問題があります。 私は答えを書いているのではなく、実際にプログラム的な方法を提供するので、+1しました。デバッグモードのwer'eがコンパイラフラグではなくコード自体の一部として表現されているかどうかを知る必要があります。 –

+1

Releaseモードでコンパイルし、DebugOutputを "none"以外に選択すると、DebuggableAttributeが存在します。だから、この答えは正しくありません。 JIT最適化フラグも検索されません。私の投稿を参照して、手動とプログラマチックの違いを伝える方法 - http://dave-black.blogspot.com/2011/12/how-to-tell-if-assembly-is-debug-or.html –

+2

一般的なケースでは、これの難しさについて@DaveBに延期する。しかし、あなたの質問は広範なものでした。あなたがテストしているときにあなたのコードが違った振る舞いをしたいのであれば、このテストは(VB.Netで) 'If System.Diagnostics.Debugger.IsAttached Then DoSomething '(フォームの動作が異なっているなど) ' –

関連する問題