Pergunta

Eu tenho uma interface que define alguns métodos com atributos. Esses atributos precisam ser acessado a partir do método de chamada, mas o método que tenho não puxa os atributos da interface. O que eu estou ausente?

public class SomeClass: ISomeInterface
{
    MyAttribute GetAttribute()
    {
        StackTrace stackTrace = new StackTrace();
        StackFrame stackFrame = stackTrace.GetFrame(1);
        MethodBase methodBase = stackFrame.GetMethod();
        object[] attributes = methodBase.GetCustomAttributes(typeof(MyAttribute), true);
        if (attributes.Count() == 0)
            throw new Exception("could not find MyAttribute defined for " + methodBase.Name);
        return attributes[0] as MyAttribute;
    }

    void DoSomething()
    {
        MyAttribute ma = GetAttribute();
        string s = ma.SomeProperty;
    }
}
Foi útil?

Solução

O MethodBase será o método na classe, e não a interface. Você vai precisar de olhar para o mesmo método na interface. Em C # isto é um pouco mais simples (uma vez que ele deve ser com o mesmo nome), mas você precisa considerar as coisas como implementação explícita. Se você tem o código VB será mais complicado, pois método VB "Foo" pode implementar um método de interface "Bar". Para fazer isso, você precisa investigar o mapa de interface:

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
interface IFoo
{
    void AAA(); // just to push Bar to index 1
    [Description("abc")]
    void Bar();
}
class Foo : IFoo
{
    public void AAA() { } // just to satisfy interface
    static void Main()
    {
        IFoo foo = new Foo();
        foo.Bar();
    }
    void IFoo.Bar()
    {
        GetAttribute();
    }

    void GetAttribute()
    { // simplified just to obtain the [Description]

        StackTrace stackTrace = new StackTrace();
        StackFrame stackFrame = stackTrace.GetFrame(1);
        MethodBase classMethod = stackFrame.GetMethod();
        InterfaceMapping map = GetType().GetInterfaceMap(typeof(IFoo));
        int index = Array.IndexOf(map.TargetMethods, classMethod);
        MethodBase iMethod = map.InterfaceMethods[index];
        string desc = ((DescriptionAttribute)Attribute.GetCustomAttribute(iMethod, typeof(DescriptionAttribute))).Description;
    }
}

Outras dicas

O método de Mark vai trabalhar para interfaces não-genéricos. Mas parece que estou lidando com alguns que têm genéricos

interface IFoo<T> {}
class Foo<T>: IFoo<T>
{
  T Bar()
}

Parece que o T é substituído pelo ClassType real nas map.TargetMethods.

Enquanto Primeiro vou confessar que eu nunca tentou anexar atributos para Interfaces mas seria algo como o seguinte trabalho para você?

public abstract class SomeBaseClass: ISomeInterface
{
     [MyAttribute]
     abstract void MyTestMethod();


}

public SomeClass : SomeBaseClass{

  MyAttribute GetAttribute(){
      Type t = GetType();
      object[] attibutes = t.GetCustomAttributes(typeof(MyAttribute), false);

      if (attributes.Count() == 0)
            throw new Exception("could not find MyAttribute defined for " + methodBase.Name);
        return attributes[0] as MyAttribute;
  }


  ....
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top