2
如何从我的类实现的接口方法检索属性?从接口方法检索属性
编辑:我不知道当时的接口,只有类的类型,或该类的一个实例。
编辑:添加了继承标志的属性,但它没有效果。
[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 {}
相关:http://stackoverflow.com/questions/1123563/are-method-attributes-inherited-in-c – 2010-02-24 21:59:20
发现这说明它的错误,但我不知道如果这是正确的仍然。它从'05 .. http://bytes.com/topic/c-sharp/answers/232588-interface-properties-custom-attributes – MatteS 2010-02-24 22:17:23
仍试图想出一个解决方法。我想我必须使用GetInterfaceMap方法使用称为InterfaceMapping的东西,但还是很想弄明白。 – MatteS 2010-03-03 20:41:21