现在的位置: 首页 > 综合 > 正文

命名方法(C# 编程指南)

2013年08月04日 ⁄ 综合 ⁄ 共 1699字 ⁄ 字号 评论关闭

 

C# 编程指南
命名方法(C# 编程指南)
 
C#
// Declare a delegate:
delegate void Del(int x);
 
// Define a named method:
void DoWork(int k) { /* ... */ }
 
// Instantiate the delegate using the method as a parameter:
Del d = obj.DoWork;
备注
作为委托参数传递的方法必须与委托声明具有相同的签名。
委托实例可以封装静态或实例方法。
尽管委托可以使用 out 参数,但不推荐将其用于多路广播事件委托中,因为无法确定要调用哪个委托。
示例 1
以下是声明及使用委托的一个简单示例。注意,委托 Del 和关联的方法 MultiplyNumbers 具有相同的签名
C#
// Declare a delegate
delegate void Del(int i, double j);
 
class MathClass
{
    staticvoid Main()
    {
        MathClass m = new MathClass();
 
        // Delegate instantiation using "MultiplyNumbers"
        Del d = m.MultiplyNumbers;
 
        // Invoke the delegate object.
        System.Console.WriteLine("Invoking the delegate using 'MultiplyNumbers':");
        for (int i = 1; i <= 5; i++)
        {
            d(i, 2);
        }
    }
 
    // Declare the associated method.
    void MultiplyNumbers(int m, double n)
    {
        System.Console.Write(m * n + " ");
    }
}
输出
Invoking the delegate using 'MultiplyNumbers':
2 4 6 8 10
示例 2
在下面的示例中,一个委托被同时映射到静态方法和实例方法,并分别返回特定的信息。
C#
// Declare a delegate
delegate void Del();
 
class SampleClass
{
    publicvoid InstanceMethod()
    {
        System.Console.WriteLine("A message from the instance method.");
    }
 
    staticpublicvoid StaticMethod()
    {
        System.Console.WriteLine("A message from the static method.");
    }
}
 
class TestSampleClass
{
    staticvoid Main()
    {
        SampleClass sc = new SampleClass();
 
        // Map the delegate to the instance method:
        Del d = sc.InstanceMethod;
        d();
 
        // Map to the static method:
        d = SampleClass.StaticMethod;
        d();
    }
}
输出
A message from the instance method.
A message from the static method.
 
 (来源:msdn )
 
【上篇】
【下篇】

抱歉!评论已关闭.