c# - 从基类访问应用于派生类中方法的属性

标签 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();
    }
}

这只会打印“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/

相关文章:

c# - 查找 xml 中所有不是标签的 'more or less than' 字符

c# - 如何使用 Roslyn 检测代码中的闭包?

.Net SvcUtil : attributes must be optional

javascript - 带有 HTML 的 jQuery html 属性?

c# - 检查参数是否具有值的 MVC 操作属性?

c# - 在 C# 中,我可以让自动属性在属性的帮助下执行一些额外的工作吗?

c# - 在 C# 中获取 Google 搜索结果

c# - 如何忽略 NodaTime nuget 包 xml 文档文件中对 jetbrains.annotations.dll 的引用

c# - 有没有办法让 C# 自定义属性在编译时引发消息?

c# - 使用自定义属性获取其成员之一的类