3

I want to hide some member vars in my C# class.
I can do this via the DebuggerBrowsable attribute:

using System.Diagnostics;

[DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]
int myvar;

However, I only want this attribute to be applied for Release builds - I want to hide the var from my assembly's Release-build consumers but I want the var visible in Debug builds for inspection during dev, etc.

I could, but would prefer not to, wrap each attribute in an #if block:

#if !DEBUG
        [DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]
#endif

That would do the trick, but creates some pretty messy-looking code.

If I were in C++/CLI - and had macros - I could do this:

#ifdef _DEBUG
#define HIDDEN_MEMBER
#else
#define HIDDEN_MEMBER   [System::Diagnostics::DebuggerBrowsableAttribute(System::Diagnostics::DebuggerBrowsableState::Never)]
#endif

and then

HIDDEN_MEMBER
int myvar;

But no macros in C# :(

Any bright ideas as to how to achieve the macro-like syntax in C#?

4

4 回答 4

2

尝试

const bool debugging = true;

接着

[DebuggerBrowsableAttribute(debugging ? DebuggerBrowsableState.Collapsed
                                      : DebuggerBrowsableState.Never)]
于 2012-08-25T19:30:31.030 回答
2

查看ConditionalAttribute 类,您可以将[Conditional]属性应用到[DebuggerBrowsable]属性。

于 2012-08-25T19:07:54.230 回答
1

Just another suggestion, using a type alias:

#if DEBUG
using HiddenMember = global::DummyAttribute.HiddenMember;
#else
using HiddenMember = global::System.Diagnostics.DebuggerBrowsableAttribute;
#endif

namespace DummyAttribute
{
    class HiddenMember : Attribute
    { public HiddenMember(DebuggerBrowsableState dummy) { } }
}

Usage:

public class YourClass
{
    [HiddenMember(DebuggerBrowsableState.Never)]
    int YourMember = 0;
}

Feel free to hide the DebuggerBrowsableState.Never argument behind a constant.

于 2012-08-26T14:47:35.170 回答
0

这是我想出的,我喜欢的东西:

In the base class:
#if DEBUG
   [DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]
   internal const System.Diagnostics.DebuggerBrowsableState BROWSABLE_ATTRIB = System.Diagnostics.DebuggerBrowsableState.Collapsed;
#else
   [DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]
   internal const System.Diagnostics.DebuggerBrowsableState BROWSABLE_ATTRIB = System.Diagnostics.DebuggerBrowsableState.Never;
#endif

这对我有用,因为我所有的对象都有一个共同的基础,无论它有多深。
请注意,我隐藏了 BROWSABLE_ATTRIB ...我不希望该 const 公开可见。

然后在任何派生类中:

[DebuggerBrowsable(BROWSABLE_ATTRIB)]
int myvar;

我更喜欢@Olivier 的回答,尽管我很感谢他发布它。
虽然每个属性中的三元组都比#if #else #endif混乱更好,但它仍然比我更喜欢的冗长。

我也不知道ConditionalAttribute;感谢@Tony。虽然它可能无法解决这种特殊情况,但我可以看到它对其他人非常有用,我很高兴将它添加到我的技巧包中。

于 2012-08-25T21:29:06.620 回答