开发者

How to instantiate a variable to call a method

开发者 https://www.devze.com 2022-12-11 12:07 出处:网络
开发者_运维知识库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

开发者_运维知识库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

精彩评论

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