简体   繁体   中英

C# solving pseudocode to help understanding delegates&lambda

I have trouble understanding lambdas, delegates and so on, I hope with someone giving me a solution to my problem I am able to understand those better. Basically it is possible to create (or change) the body of a method when an object of the class is initialized, no? Kinda like this:

Let's say I have 1 classes: Class A, which looks like this:

public class ClassA{
   int i;

   public ClassA(int number)
   {
   i = number;
   }

   public void Foo(){}
}

For demonstration purposes very minimalistic, now I also have somewhere else the static main, and what I want to do there is following: Creating multiple objects of ClassA and make it so that when I call ClassA.Foo I get different results I can determine myself, how is it supposed to look Syntax wise?

static void Main(string[] args)
{
    ClassA FooBlue = New ClassA(1){
                     public void Foo()
                     {
                     System.Console.WriteLine("I am a Fooranger Blue!");
                     };

    ClassA FooPink = New ClassA(2){
                     public void Foo()
                     {
                     System.Console.WriteLine("My  color is the manliest!");
                     };
    ...

So now when I do this:

    ...
    FooBlue.Foo();
    FooPink.Foo();
    System.Console.ReadLine();
}

I get following output on the console:

"I am a Fooranger Blue!"
"My color is the manliest!"

I just mention again that this is an example and by no means anything out of praxis but for the purpose of me understanding that stuff it would be great if someone can provide an answer that gives the desired solution, including the useless integer i.

To accomplish the goal of "providing the implementation of a method when constructing the type" you can indeed use delegates. Simply accept a delegate when constructing the object and invoke it when you want it to be executed:

public class ClassA
{
    private Action action;

    public ClassA(Action action)
    {
        this.action = action;
    }
    public void Foo()
    {
        action();
    }
}

The syntax for a lambda is different than the syntax for creating a named method from a class' definition:

var fooBlue = new ClassA(() => Console.WriteLine("I am a Fooranger Blue!"));

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