Bri*_*ink 10 .net c# attributes custom-attributes
我尝试使用下面的代码创建自定义.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()
{
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是编译器如何知道[AttributeUsage]
属性只能应用于子类System.Attribute
?使用.NET Reflector我没有看到AttributeUsageAttribute
类声明本身有什么特别之处.不幸的是,这可能只是编译器本身生成的一种特殊情况.
[Serializable, ComVisible(true), AttributeUsage(AttributeTargets.Class, Inherited=true)]
public sealed class AttributeUsageAttribute : Attribute
{
...
Run Code Online (Sandbox Code Playgroud)
我希望能够指定我的自定义属性只能放在特定类(或接口)的子类上.这可能吗?
Mar*_*ell 26
我希望能够指定我的自定义属性只能放在特定类(或接口)的子类上.这可能吗?
实际上,有一种方法可以使用子类(但不是接口)来执行此操作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; }
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2940 次 |
最近记录: |