Specify required base class for .NET attribute targets(为 .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 属性目标指定所需的基类
基础教程推荐
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01