可以在第二个方法调用中获取方法的属性

时间:2013-03-15 08:56:03

标签: c# attributes

[TestAttribute(Name = "Test")]
public void Test()
{
    Test2();
}

public viod Test2()
{
    Console.Write(TestAttribute.Name);
}

如上所示,在Test2中调用时,是否可以获取Test属性的信息?

优先不使用堆栈跟踪。

2 个答案:

答案 0 :(得分:2)

您可以使用MethodBase.GetCurrentMethod()而不是使用堆栈跟踪,并将其传递给辅助方法。

[TestAttribute(Name = "Test")]
public void Test()
{
    Test2(MethodBase.GetCurrentMethod());
}

public viod Test2(MethodBase sender)
{
    var attr = sender.GetCustomAttributes(typeof(TestAttribute), false).FirstOrDefault();
    if(attr != null)
    {
       TestAttribute ta = attr as TestAttribute;
       Console.WriteLine(ta.Name);
    }
}

答案 1 :(得分:0)

在你的情况下我不知道怎么去没有stacktrace的调用者:

[TestAttribute(Name = "Test")]
static void Test() {
    Test2();
}

static void Test2() {
    StackTrace st = new StackTrace(1);
    var attributes = st.GetFrame(0).GetMethod().GetCustomAttributes(typeof(TestAttribute), false);
    TestAttribute testAttribute = attributes[0] as TestAttribute;
    if (testAttribute != null) {
        Console.Write(testAttribute.Name);
    }
}

另一种方法是将方法信息显式传递给函数:

[TestAttribute(Name = "Test")]
void TestMethod() {
    MethodInfo thisMethod = GetType().GetMethod("TestMethod", BindingFlags.Instance | BindingFlags.NonPublic);
    Test3(thisMethod);
}

static void Test3(MethodInfo caller) {
    var attributes = caller.GetCustomAttributes(typeof(TestAttribute), false);
    TestAttribute testAttribute = attributes[0] as TestAttribute;
    if (testAttribute != null) {
        Console.Write(testAttribute.Name);
    }
}

顺便说一句,这看起来并不像你想用反射做的事情;我认为在这种情况下,方法就是这样:)

void Test() {
    Test2(name);
}

void Test2(string name) {
    Console.Write(name);
}