我知道属性非常有用。有一些预定义的属性,例如[Browsable(false)],它允许您在财产选项卡中隐藏财产。下面是一个解释属性的好问题:.NET中的属性是什么?

您在项目中实际使用的预定义属性(及其名称空间)是什么?


当前回答

作为我喜欢的中间层开发人员

System.ComponentModel.EditorBrowsableAttribute允许我隐藏财产,以便UI开发人员不会被他们不需要看到的财产淹没。

System.ComponentModel.BindableAttribute有些东西不需要数据绑定。同样,减少了UI开发人员需要做的工作。

我也喜欢劳伦斯·约翰斯顿提到的默认值。

System.ComponentModel.BrowsableAttribute和Flags定期使用。

我使用System.STAThreadAttributeSystem.ThreadStaticAttribute当需要时。

顺便说一句这些对所有.Net框架开发人员来说都同样重要。

其他回答

在霍夫斯塔德精神中,[Attribute]属性非常有用,因为它是您创建自己属性的方式。我使用了属性而不是接口来实现插件系统,为Enum添加描述,模拟多重调度和其他技巧。

如果我要进行代码覆盖率爬网,我认为这两个将是最好的:

 [Serializable]
 [WebMethod]

DesignerSerializationVisibilityAttribute非常有用。当您在控件或组件上放置运行时属性,并且不希望设计器对其进行序列化时,可以这样使用:

[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Foo Bar {
    get { return baz; }
    set { baz = value; }
}

DebuggerHiddenAttribute,它允许避免单步执行不应调试的代码。

public static class CustomDebug
{
    [DebuggerHidden]
    public static void Assert(Boolean condition, Func<Exception> exceptionCreator) { ... }
}

...

// The following assert fails, and because of the attribute the exception is shown at this line
// Isn't affecting the stack trace
CustomDebug.Assert(false, () => new Exception()); 

此外,它还防止在堆栈跟踪中显示方法,这在使用只包装另一个方法的方法时非常有用:

[DebuggerHidden]
public Element GetElementAt(Vector2 position)
{
    return GetElementAt(position.X, position.Y);
}

public Element GetElementAt(Single x, Single y) { ... }

如果现在调用GetElementAt(新的Vector2(10,10)),并且包装的方法发生错误,那么调用堆栈不会显示正在调用引发错误的方法的方法。

我喜欢将[ThreadStatic]属性与基于线程和堆栈的编程结合使用。例如,如果我希望一个值与调用序列的其余部分共享,但我希望在带外(即调用参数之外)执行,我可以使用类似的方法。

class MyContextInformation : IDisposable {
    [ThreadStatic] private static MyContextInformation current;

    public static MyContextInformation Current {
        get { return current; }
    }

    private MyContextInformation previous;


    public MyContextInformation(Object myData) {
       this.myData = myData;
       previous = current;
       current = this;
    }

    public void Dispose() {
       current = previous;
    }
}

稍后在我的代码中,我可以使用它向代码下游的人提供带外的上下文信息。例子:

using(new MyContextInformation(someInfoInContext)) {
   ...
}

ThreadStatic属性允许我将调用范围仅限于所讨论的线程,避免了跨线程访问数据的混乱问题。