cqtrq 2015-07-27 07:53 采纳率: 100%
浏览 1389
已采纳

请教关于作用域和委托的问题(附MSDN示例)

MSDN中使用回调方法检索数据的案例
https://msdn.microsoft.com/zh-cn/library/ts553s52(v=vs.110).aspx

using System;
using System.Threading;

public class ThreadWithState
{
    private string boilerplate;
    private int value; 
    private ExampleCallback callback;     

    public ThreadWithState(string text, int number, ExampleCallback callback)
    {
        boilerplate = text;
        value = number;
        this.callback = callback; 
    }    

    public void ThreadProc()
    {
        Console.WriteLine(boilerplate, value);
        if (callback != null) 
            callback(1);
    }
}

public delegate void ExampleCallback(int lineCount);

public class Example
{
    public static void Main()
    {        
        ThreadWithState tws = new ThreadWithState(  "This report displays the number {0}.",42, new ExampleCallback(ResultCallback) ); 

        Thread t = new Thread(new ThreadStart(tws.ThreadProc));
        t.Start();
        Console.WriteLine("Main thread does some work, then waits.");
        t.Join();
        Console.WriteLine( "Independent task has completed; main thread ends.");  
    }    

    public static void ResultCallback(int lineCount)
    {
        Console.WriteLine(   "Independent task printed {0} lines.", lineCount); 
    }
}

问题1:public delegate void ExampleCallback(int lineCount);这个语句,不在主程序中,也没有包含在其他的类中,为什么可以这样写?不是说“所有可执行的 C# 代码都必须包含在类中”吗?为什么ExampleCallback在public class ThreadWithState{}类中是可见的?
问题2:如果 t.Start()很快就执行完了,那么 t.Join()是否还会起作用?

  • 写回答

2条回答 默认 最新

  • cqtrq 2015-07-27 08:02
    关注

    问题1补充:为什么ExampleCallback在public class ThreadWithState{}类中是可见的?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料