问题描述
- 请教关于作用域和委托的问题(附MSDN示例)
-
MSDN中使用回调方法检索数据的案例
https://msdn.microsoft.com/zh-cn/library/ts553s52(v=vs.110).aspxusing 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()是否还会起作用?
解决方案
问题1补充:为什么ExampleCallback在public class ThreadWithState{}类中是可见的?
解决方案二:
问题1补充:为什么ExampleCallback在public class ThreadWithState{}类中是可见的?
时间: 2024-11-03 21:14:23