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 属性目标指定所需的基类


- 使用 rss + c# 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01