从接口方法中检索属性

时间:2010-02-24 21:55:18

标签: c#

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

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

编辑:在属性中添加了继承的标志,但它没有效果。

[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 {}

1 个答案:

答案 0 :(得分:2)

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