【发布时间】: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 {}
【问题讨论】:
-
发现这是一个错误,但我不知道这是否仍然正确。它来自 05..bytes.com/topic/c-sharp/answers/…
-
仍在尝试解决方法。我想我必须使用 GetInterfaceMap 方法使用名为 InterfaceMapping 的东西,但还没有弄清楚。
标签: c#