简体   繁体   中英

Cleanest way to dynamically call a non static method from a non static class?

I am looking for the cleanest way. I am tempted to use delegates not sure though.

Are you after something like this?

class A
{
    public int Value;
    public int Add(int a) { return a + Value; }
    public int Mul(int a) { return a * Value; }
}

class Program
{
    static void Main( string[] args )
    {
        A a = new A();
        a.Value = 10;
        Func<int, int> f;
        f = a.Add;
        Console.WriteLine("Add: {0}", f(5));
        f = a.Mul;
        Console.WriteLine("Mul: {0}", f(5));
    }
}

If you need the object it's called on to be unbound, like C++ member function pointers, I'm not sure that C# supports that. You can always use a lambda or delegate, though:

Func<A,int,int> f = delegate( A o, int i ) { return o.Add( i ); };
Console.WriteLine( "Add: {0}", f( a, 5 ) );
f = ( A o, int i ) => o.Mul( i );
Console.WriteLine( "Mul: {0}", f( a, 5 ) );

You might need to add more details. Delegates are a good option option, as is reflection if you only have the method name, not an actual pointer to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM