c# - 接口(interface)上的属性

标签 c# reflection attributes interface

我有一个接口(interface),它定义了一些带有属性的方法。这些属性需要从调用方法中访问,但我拥有的方法不会从接口(interface)中提取属性。我错过了什么?

public class SomeClass: ISomeInterface
{
    MyAttribute GetAttribute()
    {
        StackTrace stackTrace = new StackTrace();
        StackFrame stackFrame = stackTrace.GetFrame(1);
        MethodBase methodBase = stackFrame.GetMethod();
        object[] attributes = methodBase.GetCustomAttributes(typeof(MyAttribute), true);
        if (attributes.Count() == 0)
            throw new Exception("could not find MyAttribute defined for " + methodBase.Name);
        return attributes[0] as MyAttribute;
    }

    void DoSomething()
    {
        MyAttribute ma = GetAttribute();
        string s = ma.SomeProperty;
    }
}

最佳答案

methodBase 将是类的方法,而不是接口(interface)。您将需要在界面上寻找相同的方法。在 C# 中,这有点简单(因为它必须同名),但您需要考虑诸如显式实现之类的事情。如果你有 VB 代码,它会更棘手,因为 VB 方法“Foo”可以实现接口(interface)方法“Bar”。为此,您需要调查接口(interface)映射:

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
interface IFoo
{
    void AAA(); // just to push Bar to index 1
    [Description("abc")]
    void Bar();
}
class Foo : IFoo
{
    public void AAA() { } // just to satisfy interface
    static void Main()
    {
        IFoo foo = new Foo();
        foo.Bar();
    }
    void IFoo.Bar()
    {
        GetAttribute();
    }

    void GetAttribute()
    { // simplified just to obtain the [Description]

        StackTrace stackTrace = new StackTrace();
        StackFrame stackFrame = stackTrace.GetFrame(1);
        MethodBase classMethod = stackFrame.GetMethod();
        InterfaceMapping map = GetType().GetInterfaceMap(typeof(IFoo));
        int index = Array.IndexOf(map.TargetMethods, classMethod);
        MethodBase iMethod = map.InterfaceMethods[index];
        string desc = ((DescriptionAttribute)Attribute.GetCustomAttribute(iMethod, typeof(DescriptionAttribute))).Description;
    }
}

关于c# - 接口(interface)上的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/251806/

相关文章:

c# - DataView 行过滤

C# Remoting - 如何关闭 CustomErrors

c# - 使用数组 C# 复制文件的进度条

python - 为什么 list/dict 属性在装饰器之外保留值,而整数属性却没有?

javascript - JQuery:处理名称属性

javascript - 使用 C# 在 PhantomJS 中启用 JavaScript

java - 如何将 getMethod() 与原始类型一起使用?

java - 使用反射将可见 false 设置为按钮,可以吗?

java - 从 jar 运行时出错 - 反射 class.forname 异常

attributes - Magento2:添加产品属性作为媒体图像