首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在派生属性类型上遵守AttributeUsage

在派生属性类型上遵守AttributeUsage
EN

Stack Overflow用户
提问于 2009-10-12 11:13:50
回答 1查看 1.4K关注 0票数 5

考虑到以下情况,我不希望编译器允许从基本属性派生的多个属性(假设它被设置为AllowMultiple=false )。事实上,它编译起来没有任何问题--我在这里遗漏了什么?

代码语言:javascript
复制
using System;

[AttributeUsage(AttributeTargets.Property,AllowMultiple=false,Inherited=true)]
abstract class BaseAttribute : Attribute { }

sealed class DerivedAttributeA : BaseAttribute { }

sealed class DerivedAttributeB : BaseAttribute { }

    class Sample1
    {
        [DerivedAttributeA()]
        [DerivedAttributeB()]
        public string PropertyA{ get; set; } // allowed, concrete classes differ

        [DerivedAttributeA()]
        [DerivedAttributeA()]
        public string PropertyB { get; set; } // not allowed, concrete classes the same, honours AllowMultiple=false on BaseAttribute
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2009-10-12 11:24:41

问题很简单,AllowMultiple检查只比较相同实际类型(即实例化的具体类型)的属性-因此可能最适合与sealed属性一起使用。

例如,它将强制执行以下内容(作为非法副本),从BaseAttribute继承此内容

代码语言:javascript
复制
[DerivedAttributeB()]
[DerivedAttributeB()]
public string Name { get; set; }

简而言之,我不认为你可以在这里做你想做的事情。(强制每个属性不超过一个实例,包括BaseAttribute的子类)。

这个问题的一个类似示例是:

代码语言:javascript
复制
[Description("abc")]
[I18NDescriptionAttribute("abc")]
public string Name { get; set; }

class I18NDescriptionAttribute : DescriptionAttribute {
    public I18NDescriptionAttribute(string resxKey) : base(resxKey) { } 
}

上面的意图是在运行时提供一个来自resx的[Description] (完全由ComponentModel等支持)--但是它不能阻止你添加一个[Description]

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1553986

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档