C#委托使用详解-泛型委托(二)
小白浏览:4832022-09-02 14:32:47本文累计收益:0我也要赚钱

最近在学习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;
        }
    }
}

 

评论列表
发表评论
+ 关注