微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 为.NET属性目标指定必需的基类

我试图用下面的代码创建一个自定义.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反射器我没有看到任何特殊的AttributeUsageAttribute类声明本身.不幸的是,这可能只是编译器本身生成一个特殊情况.

[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?

实际上,有一种方法可以使用protected(见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; }
}

原文地址:https://www.jb51.cc/csharp/96423.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐