注册 登录
编程论坛 C# 论坛

delegate的问题

西安郑鑫 发布于 2014-01-22 16:45, 645 次点击
程序代码:

class A
{
    //问题1:我看好多教程里面说"delegate的定义必须放到任何类的外面",但是我看例子有些在类里面声明,而且运行正确
    public delegate void delegateDemo(int number);
   
    static void Main()
    {
        //问题2:2和4为什么可以省略new
        delegateDemo myDelegate = new delegateDemo(A.fun1);//1
//        delegateDemo myDelegate = fun1;//2
//              A a = new A();
//              delegateDemo myDelegate = new delegateDemo(a.fun2);//3
//              delegateDemo myDelegate = a.fun2;//4
    }
        //静态方法
    private static void fun1(int number)
    {
        ...
    }
        //实例方法
        private void fun2(int number)
        {
                ...
        }
}

最近学C#遇到的问题比较多,分少,望见谅
5 回复
#2
wyc1992882014-01-22 21:08
针对问题1:定义委托基本上是定义一个新类,所以可以在定义类的任何相同地方定义委托,也就是说,可以在另一个类的内部定义,也可以在任何类的外部定义,还可以在名称空间中 把委托定义为顶层对象。——参考《c#高级编程》P198。

问题2:有没有发现你的fun1后面是没有()的,有()表示方法。为了减少输入量,只要需要委托实例,就可以只传送地址的名称。这称为委托推断。只要编译器可以把委托实例解析为特定的类型,这个c#特性就是有效的。如题,fun1把方法名传递给了myDelegate。当然像你的1这样也是可以的。
#3
西安郑鑫2014-01-23 13:59
程序代码:

1    public delegate bool delegates(int number);
2    class A
3    {
4        static void Main()
5        {
6            delegates myDelegate = fun1;
7            int number;
8            fun3(number, myDelegate);
9            fun3(number, fun2);
10        }
11        private static bool fun1(int number)
12        {
13        }
14        private static bool fun2(int number)
15        {
16        }
17        private static void fun3(int number, delegates myDelegate)
18        {
19            myDelegate(a);
20            ...
21        }
22    }


fun3里面第二个参数是委托类型,里面用到了委托实例myDelegate,为什么fun2也可以直接传给fun3,而不是为fun2弄个委托变量传给fun3。
#4
西安郑鑫2014-01-23 14:26
大神出来
#5
银行2014-01-24 10:56
程序代码:
using System;
using System.Collections;

public delegate bool ComparisonHandler(int first, int second);

class DelegateSample
{
    public static void BubbleSort(int[] items, ComparisonHandler comparisonMethod)
    {

    }
    public static bool GreaterThan(int first, int second)
    {
        return first > second;
    }
    static void Main()
    {
        int[] items = new int[100];
        Random random = new Random();
        for (int i = 0; i < items.Length; ++i)
        {
            items[i] = random.Next(int.MinValue, int.MaxValue);
        }
        //委托推断
        BubbleSort(items, GreaterThan);
        for(int i = 0; i < items.Length; ++i)
        {
            Console.WriteLine(items[i]);
        }
    }
}
C# 2.0开始支持新语法叫委托推断
#6
有容就大2014-01-26 23:22
大神 好多啊 来学习。
1