2013-03-15 67 views
0
[TestAttribute(Name = "Test")] 
public void Test() 
{ 
    Test2(); 
} 

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

如上所示,Test2中调用时是否可以获取Test的属性信息?无栈跟踪可以通过第二种方法调用方法的属性

优选。

+0

当你说“没有堆栈跟踪优先”,你是什么意思?你几乎肯定需要使用'StackTrace'来找出调用方法是什么,那么为什么你要避免这种情况呢? – 2013-03-15 09:02:50

+0

为什么不用属性标记第二个方法? – Jodrell 2013-03-15 09:13:37

回答

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); 
    } 
} 
+0

我喜欢这种方法,但我认为总的来说只是将该属性与方法一起传递会更好? – 2013-03-15 09:11:29

+0

@TheunArbeider这一切都很好,但如果你改变你的方法属性呢?你的代码必须改变。我会亲自保留上面的代码,它允许更改。 – LukeHennerley 2013-03-15 09:12:56

+0

我不知道MethodBase,我的+1! – 2013-03-15 09:15:39

0

我不知道怎么去调用者没有堆栈跟踪你的情况:

[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); 
} 
+0

OP最好说没有堆栈跟踪? – LukeHennerley 2013-03-15 09:02:32

+3

我不认为这是可能的。最好意味着它不是一个严格的要求,对吧? – 2013-03-15 09:03:12

+0

您的正确和我同意,但可能会有助于解释为什么它不可能:) – LukeHennerley 2013-03-15 09:05:07

相关问题