当前位置: 移动技术网 > IT编程>开发语言>.net > .Net委托

.Net委托

2019年01月22日  | 移动技术网IT编程  | 我要评论

北京旅行社排名,斯托洛贝里,扶她奶茶futnc

委托声明

委托是一种可以指向方法的数据类型。

声明委托格式:delegate    返回值类型    委托类型名(参数);

比如delegate void mydelgate(int n);

委托实例

class program
    {
        delegate void mydel(string name);//声明委托
        static void main(string[] args)
        {
            //委托将要指向的方法必须的参数个数、类型和返回值类型都必须要与委托声明的一样
            mydel mydel = new mydel(sayhello);//这里不要写成sayhello()
            mydel("蛋蛋");//输出"蛋蛋你好"
            mydel = null;
            mydel("蛋蛋");//会抛出空引用异常
            console.readkey();
        }
        static void sayhello(string name)
        {
            console.writeline(name + "你好!");
        }
    }
}

 创建委托类型对象格式:

mydelgate mydel = new mydelgate(方法名);

也可以写成简化形式:

mydelgate mydel = 方法名;

//编译器会自动搞成new mydel (sayhello);注意方法名不能带括号

在写一个例子,获取一个数组中最大值;由于类型不定,所以最大值的算法也不一样,可以使用委托把最大算法稳定下来,把比较规则通过委托进行开放。

class program
    {
        delegate bool comparenum(object obj1, object obj2);
        static void main(string[] args)
        {
            object[] objs = { 1, 2, 4, 4, 2, 1, 2, 3 };
            //通过这样写,获取最大值的算法已经确定,在传参数的是后指定上比较方法就好了
            //用委托后,我们不在为每个获取最大值的方法都去写一种算法
            int max=(int)getmax(objs, compareint);//原生的写法为getmax(objs,new comparenum(compareint));//只不过编译器帮我们进行了处理
            console.writeline(max);
            console.readkey();
        }
//int比较方法,与委托参数一致 static bool compareint(object obj1, object obj2) { int i1 = (int)obj1; int i2 = (int)obj2; return i1 > i2; }
//获取最大值,将要比较的参数和比较使用的方法名传入,返回最大值 static object getmax(object[] obj, comparenum cpn) { object max = obj[0]; for (int i = 1; i < obj.length; i++) { if (!cpn(max, obj[i])) { max = obj[i]; } } return max; } }

 同样我们可以在写一个方法,用来比较float类型数组,使用方法和上面int类型的一样,例如

     //float比较方法,与委托参数一致
        static bool comparefloat(object obj1, object obj2)
        {
            float f1 = (float)obj1;
            float f2 = (float)obj2;
            return f1 > f2;
        }

 调用格式是:

float max=(float)getmax(objs, comparefloat);

 func、action内置泛型委托

 这个两个内置的泛型委托在micorlib的system下,使用这俩,日常开发基本不用自定义委托类型;

首先我们先看 他们的定义:func是有返回值的委托;action是没有返回值的委托

使用这个两个委托重写上面代码如下:

 class program
    {
        static void main(string[] args)
        {
            action<string> ac = new action<string>(greeting);//没有返回值的内置委托
            ac("蛋蛋");
            func<string, string> fu = new func<string, string>(greetingforr);//有返回值的内置委托
            string msg = fu("建国");
            console.writeline(msg);
            console.readkey();
        }
        static string greetingforr(string name)
        {
            return name + "你好";
        }
        static void greeting(string name)
        {
            console.writeline(name + "你好");
        }
    }

 效果显示如下,这里的ac("李诞")是不能赋值给其他变量的,因为它是没有返回值的void类型,注意也可以写成下面的简写形式,使用这两个内置委托,可以使我们的开发过程很方便。慢慢大家会感受到它们的好处。

 

匿名方法

使用delegate的时候很多时候没必要使用一个普通的方法,因为这个方法只有这个delegate会用,并且只用一次,这时候使用匿名方法最合适。

匿名方法就是没有名字的方法,格式:mydelegate p = delegate(int s){s=10;};

例如改造getmax代码

class program
    {
        delegate bool comparenum(object obj1, object obj2);
        static void main(string[] args)
        {

            object[] objs = { 1, 2, 4, 4, 2, 1, 2, 3 };
            //通过这样写,获取最大值的算法已经确定,在传参数的是后指定上比较方法就好了
            //用委托后,我们不在为每个获取最大值的方法都去写一种算法
           
        comparenum cpn = delegate (object obj1, object obj2) { int i1 = (int)obj1; int i2 = (int)obj2; return i1 > i2; }; //int max=(int)getmax(objs, compareint);//原生的写法为getmax(objs,new comparenum(compareint));//只不过编译器帮我们进行了处理 int max = (int)getmax(objs, cpn);//使用匿名方法 console.writeline(max); console.readkey(); } static bool compareint(object obj1, object obj2) { int i1 = (int)obj1; int i2 = (int)obj2; return i1 > i2; } static object getmax(object[] obj, comparenum cpn) { object max = obj[0]; for (int i = 1; i < obj.length; i++) { if (!cpn(max, obj[i])) { max = obj[i]; } } return max; } }

 委托和lambda表达式

 lambda是一种比匿名方法更加简洁的匿名方法

①lambda表达式中的参数列表(参数数量、类型和位置)必须与委托相匹配

②表达式中的参数列表不一定需要包含类型,除非委托有ref或out关键字(此时必须显示声明);

如果没有参数,必须使用一组空的圆括号

class program
    {
        delegate bool comparenum(object obj1, object obj2);
        static void main(string[] args)
        {
            //1、匿名方法
            action<string, bool> a1 = delegate (string s, bool b) {
                if (b) { console.writeline("true" + s); }
                else { console.writeline("false" + s); }
            };
            //2、简化后
            action<string, bool> a2 = (s, b) =>
            {
                if (b) { console.writeline("true" + s); }
                else { console.writeline("false" + s); }
            };
            a2("hello", true);
//1、匿名方法 func<string, int> f1 = delegate (string str) { return convert.toint32(str); };
//2、简化后 func<string, int> f2 = (str) => convert.toint32(str); ; int i = f2("1");
console.writeline(i); console.readkey(); }
}

 在看一些例子说明一下委托匿名方法和lambda表达式的转换

        //1、
            action<string, int> a11 = (s1, i1) => { console.writeline("s1=" + s1 + ",i1=" + i1); };
            //还原后
            action<string, int> a12 = delegate (string s1, int i1) {  console.writeline("s1=" + s1 + ",i1=" + i1); };
            //2、
            func<int, string> f11 = n => (n + 1).tostring();
            //还原后
            func<int, string> f12 = delegate (int n) { return (n + 1).tostring(); };
            //3、
            func<int, int> f13 = n => n * 2;
            //还原后
            func<int, int> f14 = delegate (int n) { return n * 2; };

写出下面一个lambda表达式的委托类型及非匿名函数格式

class program
    {
        static void main(string[] args)
        {

            //func<int, bool> f15 =n=>n>0;
            func<int, bool> f15 = delegate (int n) { return n > 0; };
            func<int, bool> f16 = isdyl;
            bool i=f16(-1);
            console.writeline(i);
            console.readkey();
        }
        static bool isdyl(int n)
        {
            return n > 0;
        }
    }

 使用lambda调用之前的getmax

class program
    {
        static void main(string[] args)
        {
            object[] objs = { 1, 2, 4, 4, 2, 1, 2, 3 };
            func<object, object, bool> cpn = (obj1, obj2) =>
              {
                  int i1 = (int)obj1;
                  int i2 = (int)obj2;
                  return i1 > i2;
              };
            int max = (int)getmax(objs, cpn);//使用匿名方法
            console.writeline(max);
            console.readkey();
        }
        static bool compareint(object obj1, object obj2)
        {
            int i1 = (int)obj1;
            int i2 = (int)obj2;
            return i1 > i2;
        }
        static object getmax(object[] obj, func<object,object,bool> cpn)
        {
            object max = obj[0];
            for (int i = 1; i < obj.length; i++)
            {
                if (!cpn(max, obj[i]))
                {
                    max = obj[i];
                }
            }
            return max;
        }
    }

委托深入

集合常用扩展方法:

where(支持委托)、select(支持委托)、maxminorderby

first(获取第一个,如果一个都没有则异常)

firstordefault(获取第一个,如果一个都没有则返回默认值)

single (获取唯一一个,如果没有或者有多个则异常)

singleordefault (获取唯一一个,如果没有则返回默认值,如果有多个则异常)

 这些都是集合常用的方法

 委托的组合

委托对象可以+相加”,调用组合后的新委托对象会依次调用被组合起来的委托:mydel m5 = m1+m2+m3;

组合的委托必须是同一个委托类型

(*)委托的“-”则是从组合委托中把委托移除;

(*)委托如果有返回值,则有一些特殊。委托的组合一般是给事件用的,用普通的委托的时候很少用

class program
    {
        delegate void mydel();
        static void main(string[] args)
        {
            mydel mydel = del1;
            mydel += del2;
            mydel();
            mydel -= del1;
            mydel();
            console.readkey();
        }
       static void del1()
        {
            console.writeline("第1个委托");
        }
        static void del2()
        {
            console.writeline("第2个委托");
        }
    }


                    

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网