所以我有这样一种情况,我希望能够将属性应用于派生类中的(虚拟)方法,但我希望能够提供一个使用这些属性的默认实现我的基类。
我最初的计划是覆盖派生类中的方法,只调用基实现,此时应用所需的属性,如下所示:
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();
}
}
这只会打印“A Base Value For Testing”,而不是我真正想要的其他值。
关于如何修改它以获得所需的行为,是否有人有任何建议?
最佳答案
您明确反射(reflect)了 Base
类的 GetAttributes
方法。
改为使用 GetType()
实现。如:
public virtual void GetAttributes() {
MethodInfo method = GetType().GetMethod("GetAttributes");
// ...
关于c# - 从基类访问应用于派生类中方法的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/278867/