c# - 为 .NET 属性目标指定所需的基类

标签 c# .net attributes custom-attributes

我试图用下面的代码创建一个自定义 .NET 属性,但不小心遗漏了子类。这会生成注释中显示的易于修复的编译器错误。

// results in compiler error CS0641: Attribute 'AttributeUsage' is 
// only valid on classes derived from System.Attribute
[AttributeUsage(AttributeTargets.Class)]
internal class ToolDeclarationAttribute
{
    internal ToolDeclarationAttribute()
    {
    }
}

我的问题是编译器如何知道[AttributeUsage] 属性只能应用于System.Attribute 的子类?使用 .NET Reflector 我没有看到 AttributeUsageAttribute 类声明本身有什么特别之处。不幸的是,这可能只是编译器本身生成的特例。

[Serializable, ComVisible(true), AttributeUsage(AttributeTargets.Class, Inherited=true)]
public sealed class AttributeUsageAttribute : Attribute
{
    ...

我希望能够指定我的自定义属性只能放置在特定类(或接口(interface))的子类上。这可能吗?

最佳答案

I would like to be able to specify that my custom attribute can only be placed on subclasses of a particular class (or interface). Is this possible?

实际上,有一种方法可以使用 protected 为子类(但不是接口(interface))执行此操作 - 请参阅 Restricting Attribute Usage .要重现代码(但不是讨论):

abstract class MyBase {
    [AttributeUsage(AttributeTargets.Property)]
    protected sealed class SpecialAttribute : Attribute {}
}
class ShouldBeValid : MyBase {
    [Special] // works fine
    public int Foo { get; set; }
}
class ShouldBeInvalid { // not a subclass of MyBase
    [Special] // type or namespace not found
    [MyBase.Special] // inaccessible due to protection level
    public int Bar{ get; set; }
}

关于c# - 为 .NET 属性目标指定所需的基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1190649/

相关文章:

c# - 弱引用的线程安全

DOM 元素数组上的 jQuery 选择行为

c# - Html.Label 用于使用对象的 DisplayName 而不是属性

c# - 如何让一定数量的线程一直运行

c# - 我可以将原型(prototype)反序列化为对象类型吗

c# - DLL 比较以确认是否使用相同的源代码

c# - 将一个 int 添加到它的现有数组中

python - python 类 __init__ 函数的 PyCharm 模板

ruby - Ruby 中的方法和属性有什么区别?

c# - 为什么我应该将 IHttpContextAccessor 作为单例注入(inject)