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

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


当前回答

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

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

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

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

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

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

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

其他回答

[System.Security.Permissions.PermissionSetAttribute]允许使用声明性安全性将PermissionSet的安全操作应用于代码。

// usage:
public class FullConditionUITypeEditor : UITypeEditor
{
    // The immediate caller is required to have been granted the FullTrust permission.
    [PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
    public FullConditionUITypeEditor() { }
}

我总是将DisplayName、Description和DefaultValue属性用于我的用户控件、自定义控件或我将通过属性网格编辑的任何类的公共财产。.NET PropertyGrid使用这些标记来设置未设置为默认值的名称、描述面板和粗体值的格式。

[DisplayName("Error color")]
[Description("The color used on nodes containing errors.")]
[DefaultValue(Color.Red)]
public Color ErrorColor
{
    ...
} 

如果找不到XML注释,我只希望Visual Studio的IntelliSense将Description属性考虑在内。这样可以避免同一句话重复两次。

我总是使用属性,[Serializable]、[WebMethod]、[DefaultValue]、[Description(此处为“Description”)]。

但除此之外,c#中还有一个全局属性。

[assembly: System.CLSCompliant(true)]
[assembly: AssemblyCulture("")]
[assembly: AssemblyDescription("")]

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

[XmlIgnore]

因为这允许您忽略(在任何xml序列化中)“父”对象,否则在保存时会导致异常。