指定 .NET 属性目标所需的基类
-
19-09-2019 - |
题
我尝试使用下面的代码创建自定义 .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
{
...
我希望能够指定我的自定义属性只能放置在特定类(或接口)的子类上。这可能吗?
解决方案
我希望能够指定我的自定义属性只能放置在特定类(或接口)的子类上。这可能吗?
实际上,有一种方法可以使用子类(但不是接口)来执行此操作 protected
- 看 限制属性使用. 。重现代码(但不是讨论):
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; }
}
其他提示
AttributeUsageAttribute
只是一个魔法类(如Attribute
本身)。这是一个内置的编译器规则,你不能为自己的属性做这样的事情。
使用ReSharper的可以使用[JetBrains.Annotations.BaseTypeRequired(typeof(YouBaseType))]
不隶属于 StackOverflow