c# - 从接口(interface)方法中检索属性

标签 c#

如何从我的类实现的接口(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/

相关文章:

c# - 除了方法在 linq 中如何工作

c# - 如何将 CreateObject ("Wscript.shell") 翻译成 C#

c# - 如何选择使用默认命名空间的节点?

c# - 对方法的不同级别的访问

c# - await 是否完全阻塞线程?

c# - PostMessage 到隐藏表单第一次不起作用

c# - Windows 窗体应用程序 : Displaying rows of content

c# - 在函数的字符串类型参数上使用 C# DataView.RowFilter 属性

c# - Selenium - 搜索带有类和文本的元素

c# - .NET/C# 与 Python 互操作