
// 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反射器我没有看到任何特殊的AttributeUsageAttribute类声明本身.不幸的是,这可能只是编译器本身生成的一个特殊情况.
[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?
实际上,有一种方法可以使用protected(见Restricting Attribute Usage)为子类(而不是接口)执行此 *** 作.要重现代码(但不是讨论):
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; }} 总结 以上是内存溢出为你收集整理的c# – 为.NET属性目标指定必需的基类全部内容,希望文章能够帮你解决c# – 为.NET属性目标指定必需的基类所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)