C# 委托

委托在一个方法里传递一个参数,这个参数是一个方法!回调!只是理解了一点,一个小测试!



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestWindows
{
    class Program
    {
        static void Main(string[] args)
        {

            string aaa = GetMes<string, string>(new Func<string, string>(TestString), "string");

            Console.WriteLine("a=" + aaa);

            int iii = GetMes<int, int>(new Func<int, int>(TestInt), 123);

            Console.WriteLine("i=" + iii);

            Console.ReadLine();

        }
        /// <summary>
        /// 方法一
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        public static int TestInt(int i)
        {

            return i;
        }
        /// <summary>
        /// 方法二
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string TestString(string name)
        {
            return "string: "+name;
        }

        /// <summary>
        /// 在该方法里调用方法一,二
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="func"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static TValue GetMes<TKey,TValue>(Func<TKey,TValue> func,TKey key)
        {
            var v = func(key);
            
            return v;
        }

 
    }
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C# 委托(Delegate)是一种类型,它可以用于封装一个或多个方法,使其可以像其他对象一样传递、存储和调用。委托在事件处理、多线程等方面有着广泛的应用。 C# 委托的声明方式与方法类似,可以带有参数和返回值类型,例如: ```csharp public delegate int Calculate(int a, int b); ``` 上面的代码声明了一个名为 `Calculate` 的委托类型,它包含两个 `int` 类型的参数并返回一个 `int` 类型的值。接下来可以使用这个委托类型来封装一个或多个方法。 委托的使用步骤如下: 1. 声明委托类型 ```csharp public delegate void MyDelegate(string message); ``` 2. 定义委托变量 ```csharp MyDelegate myDelegate; ``` 3. 实例化委托变量 ```csharp myDelegate = new MyDelegate(MethodA); ``` 4. 调用委托 ```csharp myDelegate("Hello"); ``` 完整的示例代码如下: ```csharp using System; namespace DelegateDemo { public delegate void MyDelegate(string message); class Program { static void Main(string[] args) { MyDelegate myDelegate; myDelegate = new MyDelegate(MethodA); myDelegate += new MyDelegate(MethodB); myDelegate("Hello"); } static void MethodA(string message) { Console.WriteLine("MethodA: " + message); } static void MethodB(string message) { Console.WriteLine("MethodB: " + message); } } } ``` 上面的代码定义了一个名为 `MyDelegate` 的委托类型,包含一个 `string` 类型的参数并返回一个 `void` 类型的值。在 `Main` 方法中,首先将 `myDelegate` 委托变量实例化为 `MethodA` 方法,然后再将其实例化为 `MethodB` 方法。最终调用 `myDelegate` 委托变量时,将会依次调用 `MethodA` 和 `MethodB` 方法。 除了以上示例中的简单委托,还有多播委托、泛型委托、匿名委托等更加高级的委托用法,可以根据具体需求选择使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值