Dynamically assign method / Method as variable

后端 未结 2 1577
傲寒
傲寒 2020-12-10 01:24

So i have 2 classes named A and B.

A has a method \"public void Foo()\".

B has several other methods.

What i need is a variable in class B, that will

相关标签:
2条回答
  • 2020-12-10 02:06

    It sounds like you want to use a delegate here.

    Basically, you can add, in class "B":

    class B
    {
        public Action TheMethod { get; set; }
    }
    
    class A
    {
        public static void Foo() { Console.WriteLine("Foo"); }
        public static void Bar() { Console.WriteLine("Bar"); }
    }
    

    You could then set:

    B b = new B();
    
    b.TheMethod = A.Foo; // Assign the delegate
    b.TheMethod(); // Invoke the delegate...
    
    b.TheMethod = A.Bar;
    b.TheMethod(); // Invoke the delegate...
    

    This would print out "Foo" then "Bar".

    0 讨论(0)
  • 2020-12-10 02:23

    Reed gave you the right answer. It's also worth pointing out that you can use other delegate signatures besides Action.

    There are generic versions like Action<T> (one arg), Action<T1, T2> (two args), etc... Also if your method has a return type, check out Func<T, TResult>.

    • Action docs: http://msdn.microsoft.com/en-us/library/018hxwa8.aspx
    • Func docs: http://msdn.microsoft.com/en-us/library/bb549151.aspx

    Or of course you can define your own delegate type.

    0 讨论(0)
提交回复
热议问题