Wednesday, November 21, 2012

[C#] Dynamic Calling Method by String 用字串動態呼叫方法

有同學問了我一個問題,他有一個 Class 裡有一堆 Method ,因為每個 Method 都對應不同情況去使用,目前是用 Switch Case 去判斷使用哪個方法,但是如果數量增加到上百上千的時候,還在用 Switch Case 感覺有點笨,於是想問問看能不能有方法去改得更聰明。

查了一下MSDN,發現有個叫做 Type.InvokeMember 的方法可以做到這點,我寫了個簡單的範例在下面,這根據所需還有很多變化方式可以做,就不一一列出了,有需要可以參考MSDN上的說明。

/// Dynamic Calling Method by String
/// </summary>
/// <param name="methodName">Method Name </param>
/// <param name="stringParam">Parameter</param>

public static void InvokeStringMethod(string methodName, string stringParam)
            Type calledType = typeof(Program);//Program是我那個class的名字

                        BindingFlags.InvokeMethod | BindingFlags.Public |
                        new Object[] { stringParam });



  1. The quality of this replica nike shoe is perfect,cheap air jordan shoes it is very comfortable to wear, wear this shoe when you travel, it will not be tired. I recommended this site to my good friends,cheap air jordan 10 they are very happy, can buy such cheap nike shoes

  2. Expect tough heels and flat styles in the Alexander McQueen women's shoe line.Cheap ALEXANDER MCQUEEN uk Discover rich and replica mens ALEXANDER MCQUEEN boot detailed decorations, such as fine embroidery on stiletto heel designs, while chunky buckles and metal studs bring discerning edges to flats. This British brand pays tribute to the trend of sports and leisure through clever sneakers with contrasting pop balls, and masculine style with open shadow loafers with striking shadows.


Related Posts Plugin for WordPress, Blogger...