【问题标题】:Retrieve Attribute from an interface method从接口方法中检索属性
【发布时间】:2011-01-20 18:07:17
【问题描述】:

如何从我的类实现的接口方法中检索属性?

编辑:我当时不知道接口,只知道类的类型,或者那个类的实例。

编辑:将继承标志添加到属性中,但没有效果。

[TestFixture]
public class MyTests {
    [Test]
    public void shouldGetMyAttribute() {
        var type = typeof (MyClass);
        var method = type.GetMethod("MyMethod");
        var attributes = method.GetCustomAttributes(true);
        var myAttribute = attributes.SingleOrDefault(x => x is MyAttributeAttribute);
        Assert.That(myAttribute, Is.Not.Null);
    }
}

public class MyClass : IMyInterface {
    public void MyMethod() {
        throw new NotImplementedException();
    }
}

public interface IMyInterface {
    [MyAttribute]
    void MyMethod();
}

[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class MyAttributeAttribute : Attribute {}

【问题讨论】:

标签: c#


【解决方案1】:

typeof(MyClass).GetInterfaces() 将返回该类实现的所有接口。从那里您可以使用类似于 Ben M 发布的代码来导航到正确的方法和属性。

【讨论】:

  • 请在代码中描述。据我所知,这并不容易。如何匹配方法?我无法按名称匹配或使用 Equals。我想我必须使用 GetInterfaceMap 方法使用称为 InterfaceMapping 的东西,但还没有弄清楚...
猜你喜欢
  • 2011-09-16
  • 1970-01-01
  • 2021-08-23
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
  • 2013-08-14
  • 2011-01-18
  • 1970-01-01
相关资源
最近更新 更多