最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - What is it called when you assign a class method to a variable? - Stack Overflow

programmeradmin1浏览0评论

In the code below, I have a class Test with a method Go. I created var Go = Test.Go, and I'm able to use either Go("stuff") or Test.Go("stuff").

What do you call assigning a class method to a variable?

var Go = Test.Go;

Go("Hello");
Test.Go("World");

class Test
{
    public static void Go(string word)
    {
        Console.WriteLine(word);
    }
}

In the code below, I have a class Test with a method Go. I created var Go = Test.Go, and I'm able to use either Go("stuff") or Test.Go("stuff").

What do you call assigning a class method to a variable?

var Go = Test.Go;

Go("Hello");
Test.Go("World");

class Test
{
    public static void Go(string word)
    {
        Console.WriteLine(word);
    }
}
Share Improve this question edited Feb 1 at 5:20 Ry- 225k56 gold badges492 silver badges498 bronze badges asked Feb 1 at 4:38 akTedakTed 2452 silver badges9 bronze badges 2
  • 3 It's called creating a delegate which has as its method the static class method. Hover over the go variable to see that it's of type Action<string> – Ivan Petrov Commented Feb 1 at 4:56
  • Ahhh, I didn't think to hover over it. I'm usually just hovering to figure out my many mistakes haha – akTed Commented Feb 1 at 10:46
Add a comment  | 

1 Answer 1

Reset to default 2

Here, you are storing as a method reference to Test.Go in the Go variable. The variable Go points a reference to the method itself ie it is a kind of function "pointer" to Test.Go.

When the method Go("Hello") is invoked , it is invoking the method using the reference. You can think of Go as a delegate or a method reference.

The reference pointer Go is especially useful when you want to pass methods around as arguments or store them for later use.

Go is more flexible, as you can pass it around, store it, or use it as a callback. Test.Go is a specific, typical direct call to the method.

发布评论

评论列表(0)

  1. 暂无评论