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 be assigned the Foo() method of class A. This variable should afterwards be "executed" (=> so it should execute the assigned method of class A).
How to do this?
A dynamic type variables are defined using the dynamic keyword. Example: dynamic Variable. dynamic MyDynamicVar = 1; The compiler compiles dynamic types into object types in most cases. However, the actual type of a dynamic type variable would be resolved at run-time.
In C# 4.0, a new type is introduced that is known as a dynamic type. It is used to avoid the compile-time type checking. The compiler does not check the type of the dynamic type variable at compile time, instead of this, the compiler gets the type at the run time.
params (C# Reference)By using the params keyword, you can specify a method parameter that takes a variable number of arguments. The parameter type must be a single-dimensional array.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With