在给定的示例中,Action Delegate是指谁?

##主要功能##

var action = new action<School>((x1) => 
                { Console.WriteLine("Hello School");
                    x1.SchoolMethod(22);
                    x1.SchoolMethod2(33,"Second Method");
                });
                action.Invoke(new School());

##课堂学校##

class School
    {
        public void SchoolMethod(int x)
        {
            Console.WriteLine($"{x}");
        }
        public void SchoolMethod2(int x,string str)
        {
            Console.WriteLine($"SchoolMethod2 {x} {str}");
        }
}

由于lambda表达式由编译器创建的方法

private static void SpecialMethodToWhichactionRefers(School school)
        {
            school.SchoolMethod(13);
            school.SchoolMethod2(22,"Bob");
        }

我正在了解action代表。我的第一个问题是关于Main Function中使用的“ action”变量。它是指编译器生成的SpecialMethodToWhichactionRefers吗? 我想问的另一个问题是将action与Classname一起使用的原因是什么。在学习过程中,我主要看到action的int,string等示例。当我们将这种类型的参数称为action时,则表示具有int和string参数的方法。我不知道为什么需要将Classname传递给action的原因。感谢您的指导。

algo5 回答:在给定的示例中,Action Delegate是指谁?

您提供类名是因为它是通用类,因此称为通用参数

其背后的原因是要知道将哪种类型的参数传递给操作,因此以后您可以使用在x1.SchoolMethod类中定义的School这样的方法调用。否则,编译器会抱怨它带有错误。

了解generic types

,
class Program
    {
        static void Main(string[] args)
        {
            Action a2 = () => Third(50);
            a2.Invoke();
        }
        public static void Third(int x)
        {
            Console.WriteLine("Third invoked");
            int result;
            result = 3 + x;
            Console.WriteLine(result);
        }
        private static void SomeSpecialName()
        {
            Third(50);
        }
    }

动作a2 =()=>第三(50);

上面的代码行将创建一个新的参数减少方法,该方法执行Third(50)方法。假设该无参数方法的名称为 SomeSpecialName 。基本上,我只想在此示例中创建类比,并在前面提出问题。在此示例中,a2将引用将执行Third(50)的无参数方法。因此,以同样的类比,可以说问题的“主要方法”中的变量“ action”也指由编译器创建的“方法”。让我们将其命名为“ SpecialMethodToWhichActionRefers ”。此 SpecialMethodToWhichActionRefers 将采用类型为学校的一个参数。

本文链接:https://www.f2er.com/3095982.html

大家都在问