开发者

How to instantiate a variable to call a method

开发者_运维知识库Is their a way in c# to instantiate a variable into a method call without using a switch statement.


It sounds like you want to take a string and use that string to call a method on an object, this can be done with reflection without the need for a switch statement.

string methodName = "ToString";
var method = typeof(TypeYourMethodExistsOn).GetMethod(methodName);
method.Invoke(objectInstance, null);


I'm not too clear, either. If you don't want to use reflection (heavy sometimes), for dynamically calling methods using a variable, you could use something like a collection containing delegates as values and call them.

I use an extremely like dictionary object to dynamically call a known method based on string inputs.

psuedo code:

delegate void Del(int i, double j);

class MathClass
{
    static void Main()
    {
        MathClass m = new MathClass();

        // Delegate instantiation using "MultiplyNumbers"
        Del d = m.MultiplyNumbers;
        Hashtable ht = new Hashtable();
        ht.Add("mult", d);

        // Invoke the delegate object.
        System.Console.WriteLine("Invoking the delegate using 'MultiplyNumbers':");
        for (int i = 1; i <= 5; i++)
        {
            ((del) ht("mult"))(i, 2);
        }
    }

    // Declare the associated method.
    void MultiplyNumbers(int m, double n)
    {
        System.Console.Write(m * n + " ");
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜