Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
131 views
Welcome To Ask or Share your Answers For Others

1 Answer

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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...