English 中文(简体)
How to instantiate a variable to call a method
原标题:
  • 时间:2009-11-17 15:23:32
  •  标签:
  • c#-3.0

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 + " ");
    }
}




相关问题
Linq - 2 tables - Sum

Asiento ******** Id_Asiento integer key Fecha date It_Asiento ********** Id_Asiento integer Forenkey Importe float I wan to do This SQL Query with Linq select Asiento.Id_Asiento, ...

Threading and un-safe variables

I have code listed here: Threading and Sockets. The answer to that question was to modify isListening with volatile. As I remarked, that modifier allowed me to access the variable from another thread....

How to cancel an asynchronous call?

How to cancel an asynchronous call? The .NET APM doesn t seem to support this operation. I have the following loop in my code which spawns multiple threads on the ThreadPool. When I click a button on ...

热门标签