如何从我的类实现的接口(interface)方法中检索属性?
编辑:当时不知道接口(interface),只知道类的类型,或者是那个类的实例。
编辑:向属性添加了继承标志,但没有任何效果。
[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 {}
最佳答案
typeof(MyClass).GetInterfaces() 将返回该类实现的所有接口(interface)。从那里您可以使用类似于 Ben M 发布的代码来导航到正确的方法和属性。
关于c# - 从接口(interface)方法中检索属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2329888/