C#基础之委托
2021-03-21 14:23
标签:可靠 debug world write 官网 cal gate with mat 官网资料:https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/delegates/ 官网复习一下委托相关概念,记录一下地址 C#基础之委托 标签:可靠 debug world write 官网 cal gate with mat 原文地址:https://www.cnblogs.com/marshhu/p/11821808.html ///
///
// Declare a delegate
delegate void Del(int i, double j);
class MathClass
{
static void Main()
{
MathClass m = new MathClass();
// Delegate instantiation using "MultiplyNumbers"
Del d = m.MultiplyNumbers;
// Invoke the delegate object.
Console.WriteLine("Invoking the delegate using ‘MultiplyNumbers‘:");
for (int i = 1; i 5; i++)
{
d(i, 2);
}
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
// Declare the associated method.
void MultiplyNumbers(int m, double n)
{
Console.Write(m * n + " ");
}
}// Declare a delegate
delegate void Del();
class SampleClass
{
public void InstanceMethod()
{
Console.WriteLine("A message from the instance method.");
}
static public void StaticMethod()
{
Console.WriteLine("A message from the static method.");
}
}
class TestSampleClass
{
static void Main()
{
var sc = new SampleClass();
// Map the delegate to the instance method:
Del d = sc.InstanceMethod;
d();
// Map to the static method:
d = SampleClass.StaticMethod;
d();
}
}
/* Output:
A message from the instance method.
A message from the static method.
*/
public delegate void Del(string message);
class TestDelegate
{
// Create a method for a delegate.
public static void DelegateMethod(string message)
{
Console.WriteLine(message);
}
public static void Test()
{
// Instantiate the delegate.
Del handler = DelegateMethod;
// Call the delegate.
handler("Hello World");
}
public static void MethodWithCallback(int param1,int param2,Del callback)
{
callback("The number is: " + (param1 + param2).ToString());
}
}
// Define a custom delegate that has a string parameter and returns void.
delegate void CustomDel(string s);
class TestClass
{
// Define two methods that have the same signature as CustomDel.
static void Hello(string s)
{
Console.WriteLine($" Hello, {s}!");
}
static void Goodbye(string s)
{
Console.WriteLine($" Goodbye, {s}!");
}
static void Main()
{
// Declare instances of the custom delegate.
CustomDel hiDel, byeDel, multiDel, multiMinusHiDel;
// In this example, you can omit the custom delegate if you
// want to and use Action