问题
Consider the following class:
[DebuggerDisplay("{GetType().Name,nq}: FileName = {FileName,nq}")]
public class FileWrapper
{
public string FileName { get; set; }
public bool IsTempFile { get; set; }
public string TempFileName { get; set; }
}
I would like to add a debugger display based on the IsTempFileName
property. I would like to add the string , TempFileName = {TempFileName,nq}
when the instance is a temp file. How would I achieve something this?
回答1:
You can use the conditional operator (?:)
[DebuggerDisplay("{GetType().Name,nq}: FileName = {FileName,nq}{IsTempFile ? \", TempFileName: \" + TempFileName : System.String.Empty,nq}")]
IsTempFile == false
IsTempFile == true
回答2:
You can use whatever expression is valid.
However, keep in mind that the debugger will evaluate these expressions a lot, so the more complicated you make them, the more you will start to noticed reduced debugging speed (e.g. when stepping through code).
Another major thing to consider is that the expression is evaluated by the debugger for the language using the class. If both the class and all its potential users are in C#, there is no problem and you can use things like the ternary operator. However, if your class is also to be used from another language, then:
- there's no guarantee the debugger will even use the [DebuggerDisplay] attribute at all,
- if it does, there's no guarantee that it will try to evaluate {expression} blocks, and
- there's a very good chance that it will fail to evaluate your C# expression if you start doing anything fancy (like using ?:)
The safest thing would be to add a private property to compute the debugger value:
[DebuggerDisplay("{DebugValue,nq}")]
public class FileWrapper {
public string FileName { get; set; }
public bool IsTempFile { get; set; }
public string TempFileName { get; set; }
private string DebugValue {
get {
var text = string.Format("{0}: FileName={1}", this.GetType(), this.FileName);
if (this.IsTempFile)
text += string.Format(", TempFileName={0}", this.TempFileName);
return text;
}
}
}
It's a private property, so it doesn't get in the way of any potential subclasses.
来源:https://stackoverflow.com/questions/12892825/is-it-possible-to-use-conditions-in-a-debuggerdisplay