从基类访问应用于派生类中的方法的属性(Accessing attributes applied to method in derived class from base class)
所以我有一个案例,我希望能够将属性应用于派生类中的(虚拟)方法,但我希望能够提供一个在我的基类中使用这些属性的默认实现。
我最初的计划是覆盖派生类中的方法,只需调用基本实现,此时应用所需的属性,如下所示:
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(); } }
这只打印“测试的基本值”,而不是我真正想要的其他值。
有没有人有任何关于我如何修改它以获得所需行为的建议?
So I've got a case where I'd like to be able to apply attributes to a (virtual) method in a derived class, but I'd like to be able to give a default implementation that uses those attributes in my base class.
My original plan for doing this was to override the method in the derived class and just call the base implementation, applying the desired attributes at this point, as follows:
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(); } }
This only prints "A Base Value For Testing", not the other values that I really want.
Does anybody have any suggestions as to how I can modify this to get the desired behavior?
原文:https://stackoverflow.com/questions/278867