C# 此委托在main方法中的用途是什么?
我正在学习关于代表的知识。这是LinkedIn C#教程中的示例代码(第一个)。我无法确定使用代表的优势和目的。不清楚原因是什么,我们不会直接调用该函数。我重新输入了自己的代码(第二个),似乎给出了类似的结果C# 此委托在main方法中的用途是什么?,c#,delegates,C#,Delegates,我正在学习关于代表的知识。这是LinkedIn C#教程中的示例代码(第一个)。我无法确定使用代表的优势和目的。不清楚原因是什么,我们不会直接调用该函数。我重新输入了自己的代码(第二个),似乎给出了类似的结果 namespace Delegates1._10._2018 { public delegate string MyDelegate(int arg1, int arg2); internal class Program { static s
namespace Delegates1._10._2018
{
public delegate string MyDelegate(int arg1, int arg2);
internal class Program
{
static string func1(int a, int b)
{
return (a + b).ToString();
}
static string func2(int a, int b)
{
return (a * b).ToString();
}
static void Main(string[] args)
{
MyDelegate f = func1;
Console.WriteLine("The number is: " + f(10,20));
f = func2;
Console.WriteLine("The number is: " + f(10,20));
}
}
}
internal class Program
{
public static int func1(int a, int b)
{
return (a + b);
}
public static int func2(int a, int b)
{
return (a * b);
}
static void Main(string[] args)
{
Console.WriteLine("The number is: " + func1(10, 20));
Console.WriteLine("The number is: " + func2(10, 20));
}
}
电话号码是:30
数字是:200委托只是声明方法的形状(
公共委托字符串MyDelegate(int arg1,int arg2)
。您可以更改调用的方法,如第一个Main
方法中所示。这是一个人为的示例,没有太多好处,因为它不处理外部数据或输入来操纵行为。委托只是声明方法的形状(公共委托字符串MyDelegate)(int arg1,int arg2);
。您可以更改调用的方法,如第一个Main
方法中所示。这是一个精心设计的示例,没有太多好处,因为它不处理外部数据或输入来操纵行为。这个示例不好。让我试着解释一下:
我们有一辆等级车,车本身不知道怎么开,坐在车里的人知道怎么开。所以车要求人(代表)开车送我
public delegate int DriveMeWithSpeed(int maxForceOnPedal);
public class Car
{
DriveMeWithSpeed speedy;
public Car(DriveMeWithSpeed YourSpeed)
{
speedy = YourSpeed;
}
public void Drive()
{
if (speedy != null) speedy(100);
}
}
public class Person
{
public int IDrive(int PedalForce)
{
return 40;
}
}
public static void Main(string[] args)
{
Person Me = new Person();
Car myCar = new Car(Me.IDrive);
myCar.Drive();
}
因此,主要的概念是类本身并不总是知道函数的功能,因此它会将其委托给知道该做什么的类。这个示例很糟糕!。让我尝试解释一下: 我们有一辆等级车,车本身不知道怎么开,坐在车里的人知道怎么开。所以车要求人(代表)开车送我
public delegate int DriveMeWithSpeed(int maxForceOnPedal);
public class Car
{
DriveMeWithSpeed speedy;
public Car(DriveMeWithSpeed YourSpeed)
{
speedy = YourSpeed;
}
public void Drive()
{
if (speedy != null) speedy(100);
}
}
public class Person
{
public int IDrive(int PedalForce)
{
return 40;
}
}
public static void Main(string[] args)
{
Person Me = new Person();
Car myCar = new Car(Me.IDrive);
myCar.Drive();
}
因此,主要的概念是类本身并不总是知道函数的功能,所以它会将其委托给知道该做什么的类。你所说的“方法的形状”是什么意思?在这两种情况下(第一种是原始的,第二种是我自己的),我以为我更改了调用的方法。但是没有使用委托。所以我不明白真正的目的。@jkuehlin查找策略模式。说“方法的形状”更好的方法是说“方法签名”。MyDelegate的签名是一种方法,它接受两个整数并返回一个字符串。键入为MyDelegate的变量可以引用具有该方法签名的任何函数,因此
func1
和func2
符合Bill您所说的“方法的形状”是什么意思h case(第一个是我自己的,第二个是我自己的),我以为我更改了调用的方法。但是没有使用委托。所以我不明白真正的目的。@jkuehlin查找策略模式。说“方法的形状”更好的方法是说“方法签名”。MyDelegate的签名是一种方法,它接受两个整数并返回一个字符串。键入为MyDelegate的变量可以引用具有该方法签名的任何函数,因此func1
和func2
符合要求