문제

속성이있는 일부 방법을 정의하는 인터페이스가 있습니다. 이러한 속성은 호출 방법에서 액세스해야하지만 내가 가진 방법은 인터페이스에서 속성을 가져 오지 않습니다. 내가 무엇을 놓치고 있습니까?

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;
    }
}
도움이 되었습니까?

해결책

메소드베이스는 인터페이스가 아닌 클래스의 메소드가 될 것입니다. 인터페이스에서 동일한 메소드를 찾아야합니다. 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()
}

t는 map.targetmethods의 실제 클라스 타입으로 대체 된 것으로 보입니다.

먼저 속성을 인터페이스에 첨부하려고 시도한 적이 없지만 다음과 같은 작업이 있습니까?

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