gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:50:29 26 4
gpt4 key购买 nike

我有一个接口(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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com