pátek 29. července 2011

Reflexe - dynamické volání metod

Dnes jsem se dostal před problém, dynamicky volat funkce v nějaké třídě. Někde budu mít uloženo jméno funkce a seznam parametrů s hodnotamy a já takto zavolám funkci. V .NETu to není samozřejmě problém díky vlastnosti zvané reflexe.

Uvádím jednoduchý příklad, pomocí kterého zavoláte funkci jejím jménem:


        public static string InvokeStringMethod(string typeName, string methodName)
        {
            // Get the Type for the class
            Type calledType = Type.GetType(typeName);

            // Invoke the method itself. The string returned by the method winds up in s
            String s = (String)calledType.InvokeMember(
            methodName,
            BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static,
            null,
            null,
            null);

            // Return the string that was returned by the called method.
            return s;
        }

Žádné komentáře: