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

Specify required base class for .NET attribute targets(为 .NET 属性目标指定所需的基类)

本文介绍了为 .NET 属性目标指定所需的基类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I tried to create a custom .NET attribute with the code below but accidentally left off the subclass. This generated an easily-fixed compiler error shown in the comment.

// 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 类声明本身有什么特别之处.不幸的是,这可能只是编译器本身生成的一种特殊情况.

My question is how does the compiler know the [AttributeUsage] attribute can only be applied to a subclass of System.Attribute? Using .NET Reflector I don't see anything special on the AttributeUsageAttribute class declaration itself. Unfortunately this might just be a special case generated by the compiler itself.

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

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

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?

推荐答案

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

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 对子类(但不是接口)执行此操作 - 请参阅 限制属性使用.重现代码(但不是讨论):

Actually, there is a way to do this for subclasses (but not interfaces) using protected - see Restricting Attribute Usage. To reproduce the code (but not the discussion):

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; }
}

这篇关于为 .NET 属性目标指定所需的基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:为 .NET 属性目标指定所需的基类

基础教程推荐