如果有多个方法符合委托标准,委托会指向哪个函数?

时间:2009-04-19 22:01:40

标签: c#

委托是一个函数指针。所以它指向一个符合标准的函数(参数和返回类型)。

这引出了一个问题(对我来说,无论如何),如果有多个方法具有完全相同的返回类型和参数类型,代表将指向哪个函数?该功能首先出现在班级中吗?

由于

3 个答案:

答案 0 :(得分:3)

创建委托时指定了确切的方法。

public delegate void MyDelegate();

private void Delegate_Handler() { }

void Init() {
  MyDelegate x = new MyDelegate(this.Delegate_Handler);
}

答案 1 :(得分:3)

正如Henk所说,在创建委托时指定了该方法。现在,有多种方法可以满足要求,原因有两个:

  • 代表是变体,例如您可以使用带有Object参数的方法来创建Action<string>
  • 您可以通过使方法变为通用来重载方法,例如

    static void Foo() {}
    static void Foo<T>(){}
    static void Foo<T1, T2>(){}
    

规则变得相当复杂,但它们已在C#3.0规范的第6.6节中规定。请注意,继承也使事情变得棘手。

答案 2 :(得分:1)

  

因此它指向符合条件的函数(参数和返回类型)。

不。

为Henk的答案添加一些背景:
就像int x是一个可以包含整数的变量一样,委托是一个可以包含函数的变量。

它指向你告诉它指向的任何功能 EG:

// declare the type of the function that we want to point to
public delegate void CallbackHandler(string); // 

...

// declare the actual function
public void ActualCallbackFunction(string s){ ... }

...
// create the 'pointer' and assign it
CallbackHandler functionPointer = ActualCallbackFunction;
// the functionPointer variable is now pointing to ActualCallbackFunction
相关问题