C# 从基类访问派生类中应用于方法的属性
所以我有一个例子,我希望能够将属性应用到派生类中的(虚拟)方法,但我希望能够给出一个默认实现,在基类中使用这些属性 我最初的计划是重写派生类中的方法,只调用基实现,在此时应用所需的属性,如下所示:C# 从基类访问派生类中应用于方法的属性,c#,attributes,custom-attributes,C#,Attributes,Custom Attributes,所以我有一个例子,我希望能够将属性应用到派生类中的(虚拟)方法,但我希望能够给出一个默认实现,在基类中使用这些属性 我最初的计划是重写派生类中的方法,只调用基实现,在此时应用所需的属性,如下所示: public class Base { [MyAttribute("A Base Value For Testing")] public virtual void GetAttributes() { MethodInfo method = typeof(Base).G
public class Base {
[MyAttribute("A Base Value For Testing")]
public virtual void GetAttributes() {
MethodInfo method = typeof(Base).GetMethod("GetAttributes");
Attribute[] attributes = Attribute.GetCustomAttributes(method, typeof(MyAttribute), true);
foreach (Attibute attr in attributes) {
MyAttribute ma = attr as MyAttribute;
Console.Writeline(ma.Value);
}
}
}
public class Derived : Base {
[MyAttribute("A Value")]
[MyAttribute("Another Value")]
public override void GetAttributes() {
return base.GetAttributes();
}
}
这只打印“用于测试的基本值”,而不是我真正想要的其他值
有人对我如何修改它以获得所需的行为有什么建议吗?您明确地反映了
Base
类的GetAttributes
方法
将实现改为使用GetType()
。例如:
public virtual void GetAttributes() {
MethodInfo method = GetType().GetMethod("GetAttributes");
// ...