c#属性还有其他有用的属性吗?

时间:2008-10-16 20:24:49

标签: c# properties attributes

  

可能重复:
  Most Useful Attributes in C#

除了:

[DefaultValue(100)]
[Description("Some descriptive field here")]
public int MyProperty{get; set;}

其他哪些C#属性对于属性有用,在学习这些之后我觉得我错过了。

相关问题

Most Useful Attributes in C#

8 个答案:

答案 0 :(得分:7)

[Obsolete("This is an obsolete property")]

这是我的最爱之一。允许您将属性/方法标记为过时,这将在构建时导致编译器警告(可选,编译器错误)。

答案 1 :(得分:3)

只是几个......

同步,内联等:

[MethodImpl]

组件模型:

[TypeDescriptor], [DisplayName], [Editor]

序列:

[Serializable], [DataMember], [XmlElement], [XmlAttribute], [NonSerialized], etc

声明性安全性:

[PrincipalPermission]

所有COM的东西......

答案 2 :(得分:2)

[Browsable]

是我的最爱。 (MSDN

答案 3 :(得分:2)

我很长一段时间都想要一个全面的c#属性列表,但从未在MSDN文档或任何地方找到过列表。我认为这是他们文档中较弱的部分之一。

如果我想从xml序列化中排除属性,我使用[XmlIgnore]。

答案 4 :(得分:1)

答案 5 :(得分:1)

如果您在多语言用户界面中使用DescriptionCategory,那么您可能会发现有用的基于资源的版本(反映自System.Windows.Forms):

[AttributeUsage(AttributeTargets.All)]
internal sealed class SRDescriptionAttribute : DescriptionAttribute
{
    private bool replaced;

    public SRDescriptionAttribute(string description) : base(description)
    {
    }

    public override string Description
    {
        get
        {
            if (!this.replaced)
            {
                this.replaced = true;
                base.DescriptionValue = SR.GetString(base.Description);
            }
            return base.Description;
        }
    }
}

[AttributeUsage(AttributeTargets.All)]
internal sealed class SRCategoryAttribute : CategoryAttribute
{
    public SRCategoryAttribute(string category) : base(category)
    {
    }

    protected override string GetLocalizedString(string value)
    {
        return SR.GetString(value);
    }
}

其中SR是相应ResourceManager的包装器。

答案 6 :(得分:0)

Localizable 以及 ListBindable 自定义组件设计师可能会感兴趣。

答案 7 :(得分:0)

我经常在枚举中使用它。枚举中是否有“默认”或“未知”值,但您不一定要绑定控件,如下拉列表?添加自定义属性,或使用现有属性来表示应该/不应该可见的项目。

我在使用具有事件代理和策略注入的框架方面做了大量工作,在使用额外元数据或松散耦合事件来装饰事件时,属性非常有用。

有一些相当新的工具,如PostSharp(http://www.postsharp.org/),可用于封装属性内的行为。在该网站上结合良好的例子;令人惊讶的是,通过这些模式编写代码会更简单。 。