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 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试