c# - 将类级别属性分配给基类,它也应该分配给所有派生类
问题描述
我有一个自定义属性
[AttributeUsage(AttributeTargets.Class)]
public sealed class CustomAttribute: Attribute
{
public CustomAttribute()
{
}
}
我在很多课程中都使用它,比如
[CustomAttribute]
public class ClassOne: MyBaseClass
{
.
.
所以我有很多从MyBaseClass派生的类,如果我想在所有类中添加这个属性,会有很多变化。我想要的是我将此属性添加到我的基类中,并且所有派生类也应该具有分配给它们的相同属性。
喜欢
[CustomAttribute]
public class MyBaseClass
{
.
.
但这并不能解决问题,我的子类仍然没有添加属性。有什么办法可以做到这一点?
解决方案
您应该[AttributeUsage(Inherited = true)]
在属性中使用属性。
[AttributeUsage(AttributeTargets.Class, Inherited = true)]
public sealed class CustomAttribute : Attribute {
public CustomAttribute() {
}
}
但它的默认值已经是 true 并且派生类应该可用于您的自定义属性。我推荐下面的示例块以确保。
首先,定义属性。
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method |
AttributeTargets.Property | AttributeTargets.Field)]
public class InheritedAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method |
AttributeTargets.Property | AttributeTargets.Field,
Inherited = false)]
public class NotInheritedAttribute : Attribute { }
[InheritedAttribute]
public class BaseA {
[InheritedAttribute]
public virtual void MethodA() { }
}
public class DerivedA : BaseA {
public override void MethodA() { }
}
[NotInheritedAttribute]
public class BaseB {
[NotInheritedAttribute]
public virtual void MethodB() { }
}
public class DerivedB : BaseB {
public override void MethodB() { }
}
然后,检查属性。
class Program {
static void Main(string[] args) {
Type typeA = typeof(DerivedA);
Console.WriteLine($"DerivedA has Inherited attribute: {typeA.GetCustomAttributes(typeof(InheritedAttribute), true).Length > 0}");
MethodInfo memberA = typeA.GetMethod(nameof(DerivedA.MethodA));
Console.WriteLine($"DerivedA.MemberA has Inherited attribute: {memberA.GetCustomAttributes(typeof(InheritedAttribute), true).Length > 0}\n");
Type typeB = typeof(DerivedB);
Console.WriteLine($"DerivedB has NotInherited attribute: {typeB.GetCustomAttributes(typeof(NotInheritedAttribute), true).Length > 0}");
MethodInfo memberB = typeB.GetMethod(nameof(DerivedB.MethodB));
Console.WriteLine($"DerivedB.MemberB has NotInherited attribute: {memberB.GetCustomAttributes(typeof(NotInheritedAttribute), true).Length > 0}");
Console.Read();
}
}
推荐阅读
- git - bgf 清洁器不更新拉取请求
- google-chrome-extension - 声音不在后台选项卡中播放
- android - 自动完成在我的 Android 工作室中不起作用
- xml - 在自闭元素之间选择文本
- c++ - 多个条件变量:线程不同步问题
- reactjs - 如何将 React webapp 集成到带有 jar 包装的 Spring Boot 应用程序中
- linux - shell脚本中字符串变量中的特殊字符
- java - 如何在 Spring Data jpa 中应用本机联接查询?
- android - 如何解决 java.io.IOException: No such file or directory or Permission denied issue on execution sh file from android in windows machine
- microsoft-information-protection - Microsoft 信息保护 SDK 1.7.133 - 加载库失败问题错误