Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从基类访问派生类中应用于方法的属性_C#_Attributes_Custom Attributes - Fatal编程技术网

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");
    // ...