C#委托使用详解-泛型委托(二) 
            
            
            
            最近在学习C#基础知识,前面学习了泛型、反射、特性,写成文章方便以后使用时查阅,本文主要记录委托最基本的内容,如果创建及使用泛型委托。
一、自定义委托使用方法
1、定义委托
delegate void GenericTest<T>(T t);
2、创建委托调用方法
public void Method1(string str)
 {
      Console.WriteLine(str);
}
3、创建委托实例
GenericTest<string> genericTest1 = new GenericTest<string>(Method1);
genericTest1("自定义泛型");
GenericTest<int> genericTest2 = new GenericTest<int>(Method2);
genericTest2(123456);
二、系统自带委托使用方法
以上是自定义委托的使用步骤,开发中一般使用系统自带的关键字定义委托,系统自带的委托包含无返回值及有返回值的委托。使用方法如下:
1、无返回值委托
Action<string> action = new Action<string>(Method1);
action("系统自带无返回值定义泛型");
2、有返回值委托
Func<string, string> func = new Func<string, string>(Method3);
Console.WriteLine(func("系统自带有返回值定义泛型"));
三、实例代码如下:
namespace TestCore
{
    delegate void GenericTest<T>(T t);
    public class TestClass
    {
        public void Test() {
            GenericTest<string> genericTest1 = new GenericTest<string>(Method1);
            genericTest1("自定义泛型");
            GenericTest<int> genericTest2 = new GenericTest<int>(Method2);
            genericTest2(123456);
            //系统自带无返回值
            Action<string> action = new Action<string>(Method1);
            action("系统自带无返回值定义泛型");
            //系统自带有返回值
            Func<string, string> func = new Func<string, string>(Method3);
            Console.WriteLine(func("系统自带有返回值定义泛型"));
        }
        public void Method1(string str)
        {
            Console.WriteLine(str);
        }
        public void Method2(int num)
        {
            Console.WriteLine(num);
        }
        public string Method3(string str)
        {
            return str;
        }
    }
}
                        猜您可能还喜欢
                    
                    
                
                    评论列表
                
                发表评论
文章分类
                
            文章归档
                - 2025年3月 (1)
- 2024年6月 (2)
- 2024年5月 (2)
- 2024年4月 (4)
- 2024年3月 (30)
- 2024年1月 (4)
- 2023年12月 (2)
- 2023年11月 (4)
- 2023年10月 (4)
- 2023年9月 (6)
- 2023年3月 (2)
- 2023年2月 (1)
- 2023年1月 (1)
- 2022年12月 (1)
- 2022年9月 (21)
- 2022年8月 (10)
- 2022年7月 (3)
- 2022年4月 (1)
- 2022年3月 (13)
- 2021年8月 (1)
- 2021年3月 (1)
- 2020年12月 (42)
- 2020年11月 (7)
- 2020年10月 (5)
- 2020年8月 (1)
- 2020年6月 (1)
- 2020年3月 (2)
- 2019年12月 (8)
- 2019年11月 (3)
- 2019年9月 (1)
- 2019年4月 (1)
- 2019年3月 (6)
- 2019年2月 (1)
- 2018年7月 (7)
阅读排行
                - 1.asp.net mvc内微信pc端、H5、JsApi支付方式总结(5876)
- 2.Windows 10休眠文件更改存储位置(3824)
- 3.各大搜索网站网站收录提交入口地址(3478)
- 4.ECharts仪表盘实例及参数使用详解(3431)
- 5.windows 10安装myeclipse 10破解补丁cracker.jar、run.bat闪退解决办法(3422)
- 6.HTML5 WebSocket与C#建立Socket连接实现代码(3179)
- 7.华为鸿蒙系统清除微信浏览器缓存方法(3170)
- 8.CERT_HAS_EXPIRED错误如何解决(2963)
- 9.Js异步async、await关键字详细介绍(lambda表达式中使用async和await关键字)(2597)
- 10.HBuilder编辑器格式化代码(2393)
 
    
