Law*_*ton 4 c# attributes custom-attributes
所以我有一个案例,我希望能够将属性应用于派生类中的(虚拟)方法,但我希望能够提供一个在我的基类中使用这些属性的默认实现.
我这样做的最初计划是覆盖派生类中的方法,然后调用基本实现,此时应用所需的属性,如下所示:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
这只打印"测试的基本值",而不是我真正想要的其他值.
有没有人建议如何修改它以获得所需的行为?
你明确反映了这个Base类的GetAttributes方法.
GetType()相反,更改要使用的实现.如:
public virtual void GetAttributes() {
MethodInfo method = GetType().GetMethod("GetAttributes");
// ...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2417 次 |
| 最近记录: |