指定.NET属性目标所需的基类 [英] Specify required base class for .NET attribute targets

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

问题描述

我试图创建与下面的code,但意外离开的子类的自定义的.NET属性。这产生在评论中所示的易于固定的编译错误。

  //导致编译器错误CS0641:属性AttributeUsage'是
//仅适用于从System.Attribute派生类
[AttributeUsage(AttributeTargets.Class)
内部类ToolDeclarationAttribute
{
    内部ToolDeclarationAttribute()
    {
    }
}
 

我的问题是如何编译器知道 [AttributeUsage] 属性只能应用到子类 System.Attribute ?使用.NET反射我看不出有什么特别的 AttributeUsageAttribute特性类声明本身。不幸的是,这可能仅仅是由编译器本身产生的一个特例。

  [Serializable接口,标记有ComVisible特性(真),AttributeUsage(AttributeTargets.Class,继承=真)
公共密封类AttributeUsageAttribute特性:属性
{
    ...
 

我想可以指定我的自定义属性只能被放置在一个特定的类(或接口)的子类。这可能吗?

解决方案
  

我想可以指定我的自定义属性只能被放置在一个特定的类(或接口)的子类。这可能吗?

其实,有一种方法可以做到这一点,使用受保护的子类(而不是接口) - 看的Restricting属性用法。要重现code(但不讨论):

 抽象类MyBase {
    [AttributeUsage(AttributeTargets.Property)
    保护密封类SpecialAttribute:属性{}
}
类ShouldBeValid:MyBase {
    [专题] //工作正常
    公众诠释富{获得;组; }
}
MyBase的类ShouldBeInvalid {//不是一个子类
    [专题] //类型或命名空间找不到
    [MyBase.Special] //人迹罕至,由于保护级别
    公众诠释吧{获得;组; }
}
 

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()
    {
    }
}

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?

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属性目标所需的基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆