Store methods in an array and call them in C #

In javascript we can do this:

var arr = [];

function fooBar() {
    console.log('Hello World');
}

arr[0] = fooBar;

arr[0]();

In fact, each function is a real object, and I can save them in an array if I want. My question is that C # has no pointers, what is the best way to handle such scenarios? I mean, how can I store function references in arrays?

I know that we have something called delegates, but I'm not sure if this is right for the task ...

+4
source share
6 answers

Delegates are exactly what you need:

var list = new List<Action>();

...

void fooBar() {
    ....
}

...

list.Add(fooBar);

Action , delegate, , , . , , Action<T>. , -, Func -delegate.

EDIT: , , , delegate:

var list = new List<Delegate>();

, DynamicInvoke .

list[0].DynamicInvoke(args);
+8

- .

, , System.Delegate, , - , .

:

public static String Meow(Cat cat) { return "meow"; }
public static String Purr(Cat cat) { return "purr"; }

delegate String CatSound(Cat cat);

CatSound[] catSounds = new CatSound[] {
    Meow,
    Purr
};

:

Cat orion = new Cat();
catSounds[0]( orion ); // meow
catSounds[1]( orion ); // purr

DogSound , : Delegate[]...

delegate String DogSound(Dog dog);

Delegate[] petSounds = new Delegate[] {
    new CatSound( Meow ),
    new CatSound( Purr ),
    new DogSound( Woof ),
    new DogSound( Bark ),
}; // note that C# compiler allows shorthand syntax where simply `Meow` is behind-the-scenes converted into `new CatSound( Meow )`.

... DynamicInvoke (https://msdn.microsoft.com/en-us/library/system.delegate.dynamicinvoke(v=vs.110).aspx), , , , , MemberAccessException.

Dog pupper = new Dog();
Cat orion = new Cat();

petSounds[0].DynamicInvoke( orion );
petSounds[1].DynamicInvoke( orion );
petSounds[2].DynamicInvoke( pupper ); // ok, this is a DogSound
petSounds[3].DynamicInvoke( orion ); // this will fail at runtime because you're passing a Cat into a DogSound delegate

delgates "a interface ".

.NET Framework 3.5 delegate ( , delegate # 3.0), System.Action System.Func, 95% , . , delegate CatSound , Func<Cat,String>.

+5

, , , generics .

Func<int,int> Square = x => x*x;
Func<int,int> Successor = x => x+1;
Func<int,int> Functions[] = new Func<int,int>[]{ Square, Successor };

int A = Functions[0](2); // A gets assigned 4;
int B = Functions[1](1); // B gets assigned 2;
+2

Action Func, :

void Main()
{
    var arr = new object[2];
    arr[0] = 1;
    arr[1] = (Action)DoIt;

    foreach (var a in arr)
    {
        if (a is Action)
        {
            ((Action)a)();
        }
        else
        {
            Console.WriteLine(a.ToString());
        }
    }
}


public void DoIt()
{
    Console.WriteLine("did");       
}
+2

( .net verion)

https://msdn.microsoft.com/en-us/library/018hxwa8(v=vs.110).aspx

List<Action<string>> actions = new List<Action<string>>();

    actions.Add(() => {
      //do stuff
    });

or if you need rturn values, use Func: https://msdn.microsoft.com/en-us/library/bb549151(v=vs.110).aspx

+1
source

Through delegates, you can:

static void iammain()
{
  List<Action> lst = new List<Action>();
  lst.AddRange(new Action[] { proc1, proc2, proc3 });
  for (int i = 0; i < lst.Count; i++)
  {
    lst[i]();

  }

}
static void proc1()
{
  Console.WriteLine("i am proc1");

}
static void proc2()
{
  Console.WriteLine("i am proc2");

}
static void proc3()
{
  Console.WriteLine("i am proc3");

}
+1
source

Source: https://habr.com/ru/post/1669374/


All Articles