【问题标题】:Is restricting attributes to class or properties doable?将属性限制为类或属性是否可行?
【发布时间】:2011-02-22 11:41:44
【问题描述】:

我有两个这样定义的自定义属性:

internal class SchemaAttribute : Attribute {
    internal SchemaAttribute(string schema) {
        Schema = schema;
    }

    internal string Schema { get; private set; }
}

internal class AttributeAttribute : Attribute {
    internal AttributeAttribute(string attribute) {
        Attribute = attribute;
    }

    internal string Attribute { get; private set; }
}

我想将 SchemaAttribute 限制为类,将 AttributeAttribute 限制为属性。

这可行吗?

【问题讨论】:

  • 如果您发现我的问题足以帮助其他人,请点赞。谢谢! =)

标签: c# vb.net .net-2.0 attributes custom-attributes


【解决方案1】:

查看AttributeUsageAttributeTargets

它看起来像:

[AttributeUsage(AttributeTargets.Class)]
internal class SchemaAttribute : Attribute
{
    // Implementation
}

[AttributeUsage(AttributeTargets.Property)]
internal class AttributeAttribute : Attribute
{
    // Implementation
}

【讨论】:

  • +1。 AttributeTargets 不是 AttributeTarget,我无法修复您的帖子,因为 SO 要求您每个答案至少有 6 个错别字:-(
【解决方案2】:

AttributeTargetAttribute

[AttributeTarget(AttributeTargets.Class)]
internal class SchemaAttribute : Attribute
...

[AttributeTarget(AttributeTargets.Property)]
internal class AttributeAttribute: Attribute
...

【讨论】:

    猜你喜欢
    • 2020-03-17
    • 2013-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多