質問

いくつかのメソッドに属性を定義するインターフェイスがあります。これらの属性は呼び出し元のメソッドからアクセスする必要がありますが、私が持っているメソッドはインターフェースから属性をプルしません。何が足りないのですか?

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;
    }
}
役に立ちましたか?

解決

methodBaseは、インターフェイスではなく、クラスのメソッドになります。インターフェイスで同じメソッドを探す必要があります。 C#では、これは少し単純です(名前が似ている必要があるため)が、明示的な実装などを考慮する必要があります。 VBメソッドがある場合、VBメソッド" Foo"インターフェイスメソッド「バー」を実装できます。これを行うには、インターフェイスマップを調査する必要があります。

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;
    }
}

他のヒント

Markのメソッドは、非ジェネリックインターフェイスに対して機能します。しかし、私はジェネリックを持っているものを扱っているようです

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

map.TargetMethodsのTは実際のclassTypeに置き換えられているようです。

最初に、インターフェイスに属性をアタッチしようとしたことはありませんが、次のようなことができると思いますか?

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;
  }


  ....
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top