2013-03-15 68 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

相關問題