Profilo di 陈琪i am a failer?FotoBlogElenchiAltro Strumenti Guida
Foto 1 di 166

i am a failer?

Where is the sunrise
16 agosto

方向连接工具及Vista+安全特性

前些日子在开发一个反向连接工具,就是公司电脑连接家里的电脑,但却是家里的电脑控制公司电脑。其实原理很简单,关键是家中的电脑都是动态获得IP的,公司机器如何获得IP?
步骤是这样的,
  1. 首先当然学要一些第三方的远程控制软件,这一部分,我目前的技术还是很难实现。RealVnc不错。
  2. 两方都安装好此VNC,公司机器开Server端,家里开Listening。
  3. 家里一上网,利用SMTP协议发送IP地址到指定邮箱。
  4. 公司机器不断轮询,利用POP3搜索邮箱,一旦有IP信心更新,发送命令,反向连接家里的机器

其实都很简单,但是第4步,在Vista上用Windows Service轮询,并用Process.Start起进程效果和XP上完全不一样。为什么会这样呢?

Vista安全机制所致,一般System Account起的进程都在Session0,而当前用户的进程都在Session1,当你安装好服务后,如果用LocalSystem account安装的service,并希望与桌面交互,则完全没有反应,因为在两个隔离的session中。

如果用当前用户帐号安装服务,则会有一个提示框,提醒你有一个程序需要确认运行,如果你点击确定,OS则会跳转到另一个新的桌面运行。这跟以往的特性和开发目的是不一样的。经过一段时间的搜索,终于解决问题了

 

需要使用P-Invoke,首先获得当前用户进程的Handle,然后进一步获得Token,因为它是一个Impersonate的Token,于是需要elevate此Token至PrimaryToken,然后调用CreateProcessAsUser 其进程,那样一切都OK了:)
23 ottobre

User Account Control

User Account Control (UAC) is a technology and security infrastructure introduced with Microsoft's Windows Vista operating system. It aims to improve the security of Microsoft Windows by limiting application software to standard user privileges until an administrator authorizes an increase in privilege level. In this way, only applications that the user trusts receive higher privileges, and malware should be kept from receiving the privileges necessary to compromise the operating system. In other words, a user account may have administrator privileges assigned to it, but applications that the user runs do not also have those privileges unless they are approved beforehand or the user explicitly authorizes it to have higher privileges.

To reduce the possibility of lower-privilege applications communicating with higher-privilege ones, another new technology, User Interface Privilege Isolation is used in conjunction with User Account Control to isolate these processes from each other.[1] One prominent use of this is Internet Explorer 7's "Protected Mode".[2]

Contents

History

Differentiation of a superuser and userland has been common in mainframes and servers for decades. This had an obvious security component, but also an administrative component, in that it prevented users from accidentally changing system settings.

Microsoft home operating systems (such as Windows 95, Windows 98 and Windows Me) did not have a concept of different user accounts on the same machine, and all actions were performed as super user. Windows NT introduced multiple user accounts, but in practice most users continued to operate as super user administrator for their normal operations. Further, many applications tend to assume that the user is super user, and will simply not work if they are not.[3]

Subsequent versions of Windows and Microsoft applications have encouraged the use of non-administrator user logins, but the uptake has been slow. User Account Control is a stronger approach to do this introduced in Vista. But it is difficult to introduce new security features without breaking existing applications.

When logging into Vista as a standard user, a logon session is created and a token containing only the most basic privileges is assigned. In this way, the new logon session is incapable of making changes that would affect the entire system. When logging in as a user in the Administrators group, two separate tokens are assigned. The first token contains all privileges typically awarded to an administrator, and the second is a restricted token similar to what a standard user would receive. User applications, including the Windows Shell, are then started with the restricted token, resulting in a reduced privilege environment even under an Administrator account. When an application requests higher privileges or "Run as administrator" is clicked, UAC will prompt for confirmation and, if consent is given, start the process using the unrestricted token.[4]

Tasks that trigger a UAC prompt

Please help improve this section by expanding it. Further information might be found on the talk page or at requests for expansion. (June 2008)
Operating system commands or actions that require administrator rights (and will thus trigger UAC) are marked with the security shield symbol.
Operating system commands or actions that require administrator rights (and will thus trigger UAC) are marked with the security shield symbol.

Tasks that require administrator privileges will trigger a UAC prompt (if UAC is enabled) are typically marked by a 4-color security shield symbol. In the case of executable files, the icon will have a security shield overlay. Ed Bott's Windows Vista Inside Out lists the following tasks which require administrator privileges:[5]

  • Changes to system-wide settings or to files in %SystemRoot% or %ProgramFiles%
  • Installing and uninstalling applications
  • Installing device drivers
  • Installing ActiveX controls
  • Changing settings for Windows Firewall
  • Changing UAC settings
  • Configuring Windows Update
  • Adding or removing user accounts
  • Changing a user’s account type
  • Configuring Parental Controls
  • Running Task Scheduler
  • Restoring backed-up system files
  • Viewing or changing another user’s folders and files

Common tasks, such as changing the time zone, do not require administrator privileges[6] (although changing the system time itself does, since the system time is commonly used in security protocols). A number of tasks that required administrator privileges in earlier versions of Windows, such as installing critical Windows updates, no longer do so in Vista.[7] Any program can be run as administrator by right-clicking its icon and clicking "Run as administrator".

Features

User Account Control asks for credentials in a Secure Desktop mode, where the entire screen is temporarily darkened and Windows Aero disabled and only the authorization window is enlightened, to present only the elevation user interface (UI). This is to prevent spoofing of the UI or the mouse by the application requesting elevation.[8] If an administrative activity comes from a minimized application, the secure desktop request will also be minimized so as to prevent the focus from being lost. It is possible to disable Secure Desktop, though this is inadvisable from a security perspective.[9]

Applications written with the assumption that the user will be running with administrator privileges experienced problems in earlier versions of Windows when run from limited user accounts, often because they attempted to write to machine-wide or system directories (such as Program Files) or registry keys (notably HKLM)[3]. UAC attempts to alleviate this using File and Registry Virtualization, which redirects writes (and subsequent reads) to a per-user location within the user’s profile. For example, if an application attempts to write to “C:\program files\appname\settings.ini” and the user doesn’t have permissions to write to that directory, the write will get redirected to “C:\Users\username\AppData\Local\VirtualStore\Program Files\appname\settings.ini”.

There are a number of configurable UAC settings. It is possible to:[10]

  • Require administrators to re-enter their password for heightened security;
  • Require the user to press Ctrl+Alt+Del as part of the authentication process for heightened security;
  • Disable Admin Approval Mode (UAC prompts for administrators) entirely;

Command Prompt windows that are running elevated will prefix the title of the window with the word "Administrator", so that a user can discern which instances are running with elevated privileges.[11]

A distinction is made between elevation requests from a signed executable and an unsigned executable; and if the former, whether the publisher is 'Windows Vista'. The color, icon, and wording of the prompts are different in each case; for example, attempting to convey a greater sense of warning if the executable is unsigned than if not.[12]

Internet Explorer 7's "Protected Mode" feature uses UAC to run with a 'low' integrity level (a Standard user token has an integrity level of 'medium'; an elevated (Administrator) token has an integrity level of 'high'). As such, it effectively runs in a sandbox, unable to write to most of the system (apart from the Temporary Internet Files folder) without elevating via UAC.[4][13] Since toolbars and ActiveX controls run within the Internet Explorer process, they will run with low privileges as well, and will be severely limited in what damage they can do to the system.[14]

Configuration

UAC Tick Box
UAC Tick Box

UAC can be configured via security settings (secpol.msc -> Local Policies -> Security Options), though this is only available for the Business and Ultimate editions. All configuration items are prefixed with “User Account Control”.

  • 'Behaviour of the elevation prompt for administrators in admin approval mode'. Can be set to:
    • 'Turn off UAC' (no prompt).
    • 'Prompt for consent' (default).
    • 'Prompt for credentials'.
  • 'Behaviour of the elevation prompt for standard users'. This setting determines what happens if you run as a standard user and start a program that needs administrator rights (for the cases UAC can determine admin rights are required e.g. does not work for MMC snapins). Can be set to:
    • 'No prompt: fail and do not start the program if it required admin rights'.
    • 'Prompt for credentials' (default).
  • 'Admin approval mode for the built-in administrator account'. This setting can be used to disable UAC for the built-in Administrator account. Can be set to 'Enable' or 'Disable'. The built-in administrator account is disabled by default in Windows Vista. The default value of this setting depends on the configuration and on how the system was installed - see http://msdn.microsoft.com/en-us/library/bb756883.aspx for discussion.
  • 'Detect application installations and prompt for elevation'. Windows by default uses some heuristics to determine if an EXE is an installer (which most likely requires elevation). Can be set to 'Enable' (the default) or 'Disable'.
  • 'Switch to the secure desktop when prompting for elevation'. Can be set to 'Enable' (the default) or 'Disable'.
  • 'Only execute executables that are signed and validated'. If enabled an additional check is done after the elevation prompt. If the EXE is not signed the EXE will not be started. Can be set to 'Enable' or 'Disable' (the default).
  • 'Virtualize file and registry write failures to per-user locations'. Can be set to 'Enable' (the default) or 'Disable'.
  • 'Run all administrators in Admin Approval Mode'. To switch off UAC set this setting to disabled and reboot. All UAC behavior will be disabled, including file and registry virtualization. Can be set to 'Enable' (the default) or 'Disable'.

An alternate method to configure UAC and switch it off:

  • Create a new text file in notepad
  • enter the following:

C:\Windows\System32\cmd.exe /k %windir%\System32\reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 0 /f
pause

  • Save the text file as
    • Save as type: All Files
    • Name: UAC_Off.bat
  • Right click on the new file and run as administrator
  • Restart.

To switch UAC back on using this method, repeat the above steps, but save the file as UAC_On.bat and enter the following instead:
C:\Windows\System32\cmd.exe /k %windir%\System32\reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 1 /f
pause

Requesting elevation

A program can request elevation in a number of different ways. One way for program developers is to add a requestedPrivileges section to an XML document, known as the manifest, that is then embedded into the application. A manifest can specify dependencies, visual styles, and now the appropriate security context:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <v3:trustInfo xmlns:v3="urn:schemas-microsoft-com:asm.v3">
    <v3:security>
      <v3:requestedPrivileges>
        <v3:requestedExecutionLevel level="highestAvailable" />
      </v3:requestedPrivileges>
    </v3:security>
  </v3:trustInfo>
</assembly>

Setting the level attribute for requestedExecutionLevel to "asInvoker" will make the application run with the token that started it, "highestAvailable" will present a UAC prompt for administrators and run with the usual reduced privileges for standard users, and "requireAdministrator" will require elevation.[15] In both highestAvailable and requireAdministrator modes, failure to provide confirmation results in the program not being launched.

An executable that is marked as "requireAdministrator" in its manifest cannot be started from a non-elevated process using CreateProcess(). Instead, ERROR_ELEVATION_REQUIRED will be returned. ShellExecute() or ShellExecuteEx() must be used instead. If an HWND is not supplied, then the dialog will show up as a blinking item in the taskbar.

Inspecting an executable's manifest to determine if it requires elevation is not recommended, as elevation may be required for other reasons (setup executables, application compatibility). However, it is possible to programmatically detect if an executable will require elevation by using CreateProcess() and setting the dwCreationFlags parameter to CREATE_SUSPENDED. If elevation is required, then ERROR_ELEVATION_REQUIRED will be returned.[16] If elevation is not required, a success return code will be returned at which point you can use TerminateProcess() on the newly created, suspended process. This will not allow you detect that an executable requires elevation if you are already executing in an elevated process, however.

A new process with elevated privileges can be spawned from within a .NET application using the "runas" verb. An example using C++/CLI:

System::Diagnostics::Process^ proc = gcnew System::Diagnostics::Process();
proc->StartInfo->FileName = "C:\\Windows\\system32\\notepad.exe";
proc->StartInfo->Verb = "runas"; // Elevate the application
proc->Start();

In a native Win32 application the same "runas" verb can be added to a ShellExecute() or ShellExecuteEx() call.[4]

ShellExecute(hwnd, "runas", "C:\\Windows\\Notepad.exe", 0, 0, SW_SHOWNORMAL);

In the absence of a specific directive stating what privileges the application requests, UAC will apply heuristics, to determine whether or not the application needs administrator privileges. For example, if UAC detects that the application is a setup program, from clues such as the filename, versioning fields, or the presence of certain sequences of bytes within the executable, in the absence of a manifest it will assume that the application needs administrator privileges.[17]

Criticism

There have been complaints that UAC notifications slow down various tasks on the computer such as the initial installation of software onto Windows Vista.[18] It is possible to turn off UAC while installing software, and reenable it at a later time.[19] However, this is not recommended since, as File & Registry Virtualization is only active when UAC is turned on, user settings and configuration files may be installed to a different place (a system directory rather than a user-specific directory) if UAC is switched off than they would be otherwise.[20] Also note that Internet Explorer 7's "Protected Mode", whereby the browser runs in a sandbox with lower privileges than the standard user, relies on UAC; and will not function if UAC is disabled.[13]

Yankee Group analyst Andrew Jaquith stated that "while the new security system shows promise, it is far too chatty and annoying."[21] However, this statement was made over six months before Vista was actually released (even before Beta 2 was released). By the time Windows Vista was released in November 2006, Microsoft had drastically reduced the number of operating system tasks that triggered UAC prompts, and added file and registry virtualization to reduce the number of legacy applications that trigger UAC prompts.[3] However, David Cross, a product unit manager at Microsoft, stated during the RSA Conference 2008 that UAC was in fact designed to "annoy users", and force independent software vendors to make their programs more secure so that UAC prompts would not be triggered.[22]

See also

References

  1. ^ "The Windows Vista and Windows Server 2008 Developer Story: Windows Vista Application Development Requirements for User Account Control (UAC)". The Windows Vista and Windows Server 2008 Developer Story Series. Microsoft (April 2007). Retrieved on 2007-10-08.
  2. ^ "Understanding and Working in Protected Mode Internet Explorer". Microsoft (January 2006). Retrieved on 2007-12-08.
  3. ^ a b c Torre, Charles (March 5, 2007). "UAC - What. How. Why." (video). Retrieved on 2007-12-08.
  4. ^ a b c Kerr, Kenny (September 29, 2006). "Windows Vista for Developers – Part 4 – User Account Control". Retrieved on 2007-03-15.
  5. ^ Bott, Ed (2007-02-02). "What triggers User Account Control prompts?".
  6. ^ Allchin, Jim (2007-01-23). "Security Features vs. Convenience". Windows Vista Team Blog. Microsoft. Retrieved on 2007-03-04.
  7. ^ "User Account Control Overview". Technet.
  8. ^ "User Account Control Prompts on the Secure Desktop". UACBlog. MSDN Blogs (2006-05-03). Retrieved on 2007-02-25.
  9. ^ Bott, Ed (February 2, 2007). "Why you need to be discriminating with those Vista tips". Ed Bott's Windows Expertise. Retrieved on 2007-12-08.
  10. ^ "Chapter 2: Defend Against Malware". Windows Vista Security Guide. Microsoft (November 8, 2006). Retrieved on 2007-03-15.
  11. ^ "Administrator Marking for Command Prompt". UACBlog. MSDN Blogs (August 1, 2006). Retrieved on 2006-08-07.
  12. ^ "Accessible UAC Prompts". Windows Vista Blog. Microsoft.
  13. ^ a b Russinovich, Mark (June 2007). "Inside Windows Vista User Account Control". TechNet Magazine. Microsoft. Retrieved on 2007-12-08.
  14. ^ Friedman, Mike. "Protected Mode in Vista IE7". IEBlog.
  15. ^ Mike Carlisle (2007-03-10). "Making Your Application UAC Aware". The Code Project. Retrieved on 2007-03-15.
  16. ^ Junfeng Zhang (2006-10-18). "Programmatically determine if an application requires elevation in Windows Vista". MSDN Blogs. Retrieved on 2008-01-24.
  17. ^ "Understanding and Configuring User Account Control in Windows Vista". Microsoft. Retrieved on 2007-07-05.
  18. ^ "Disabling the UAC feature" (2007-03-10). Retrieved on 2007-03-10.
  19. ^ "Windows Vista upgrade power tips".
  20. ^ Bott, Ed (2007-02-02). "Why you need to be discriminating with those Vista tips". Ed Bott's Windows Expertise. Retrieved on 2007-07-05.
  21. ^ Evers, Joris (2006-05-07). "Report: Vista to hit anti-spyware, firewall markets". ZDNet News. CNet. Retrieved on 2007-01-21.
  22. ^ Microsoft: Vista feature designed to 'annoy users' | Tech News on ZDNet

External links

22 ottobre

How can I read the memory dump files that Windows creates for debugging?

Small memory dump files


A small memory dump file records the smallest set of useful information that may help identify why your computer has stopped unexpectedly. This option requires a paging file of at least 2 megabytes (MB) on the boot volume. On computers that are running Microsoft Windows 2000 or later, Windows create a new file every time your computer stops unexpectedly. A history of these files is stored in a folder.

This dump file type includes the following information:

  • The Stop message and its parameters and other data
  • A list of loaded drivers
  • The processor context (PRCB) for the processor that stopped
  • The process information and kernel context (EPROCESS) for the process that stopped
  • The process information and kernel context (ETHREAD) for the thread that stopped
  • The Kernel-mode call stack for the thread that stopped

The small memory dump file can be useful when hard disk space is limited. However, because of the limited information that is included, errors that were not directly caused by the thread that was running at the time of the problem may not be discovered by an analysis of this file.

If a second problem occurs and if Windows creates a second small memory dump file, Windows preserves the previous file. Windows gives each file a distinct, date-encoded file name. For example, Mini022900-01.dmp is the first memory dump file that was generated on February 29, 2000. Windows keeps a list of all the small memory dump files in the %SystemRoot%\Minidump folder.


Configure the dump type


To configure startup and recovery options to use the small memory dump file, follow these steps.

Note: Because there are several versions of Microsoft Windows, the following steps may be different on your computer. If they are, see your product documentation to complete these steps.

  1. Click Start, point to Settings, and then click Control Panel.
  2. Double-click System.
  3. Click the Advanced tab, and then click Settings under Startup and Recovery.
  4. In the Write debugging information list, click Small memory dump (64k).

    To change the folder location for the small memory dump files, type a new path in the Dump File box (or in the Small dump directory box, depending on your version of Windows).



Tools to read the small memory dump file


You can load small memory dump files by using the Dump Check Utility (Dumpchk.exe). You can also use Dumpchk.exe to verify that a memory dump file has been created correctly. The Dump Check Utility does not require access to debugging symbols. The Dump Check Utility is included with the Microsoft Windows 2000 Support Tools and the Microsoft Windows XP Support Tools.

For additional information about how to use the Dump Check Utility in Windows 2000 and in Windows NT, view the article in the Microsoft Knowledge Base How to use Dumpchk.exe to check a memory dump file

For additional information about how to use the Dump Check Utility in Windows XP, view the article in the Microsoft Knowledge Base: How to use Dumpchk.exe to check a memory dump file

Note: The Dump Check Utility is not included in the Microsoft Windows Server 2003 Support Tools. To obtain the Dump Check Utility if you are using Microsoft Windows Server 2003, download and install the Debugging Tools for Windows package from the Microsoft’s Web site.

You can also read small memory dump files by using the WinDbg tool or the KD.exe tool. WinDbg and KD.exe are included with the latest version of the Debugging Tools for Windows package.

This Web page also provides access to the download symbol packages for Windows. To use the resources, create a folder on the disk drive where the downloaded local symbols or the symbol cache for symbol server use will reside; for example, use C:\Symbols.

  • NOTE: To use the Microsoft Symbol Server. Make sure you have installed the latest version of Debugging Tools for Windows.

    You can use the following symbol path with all the commands that are described in this article:

    • NOTE: Start a debugging session.

      Set the debugger symbol path as follows, substituting your symbols path with C:\symbols.

      SRV*c:\symbols*http://msdl.microsoft.com/download/symbols

      For additional information about the dump file options in Windows, go to Overview of memory dump file options for Windows 2000, for Windows XP, and for Windows Server 2003


      Install the debugging tools


      To download and install the Windows debugging tools, visit Debugging Tools and Symbols: Getting Started

      Select the Typical installation. By default, the installer installs the debugging tools in the following folder:

      • C:\Program Files\Debugging Tools for Windows



        Open the dump file


        To open the dump file after the installation is complete, follow these steps:

        1. Click Start, click Run, type cmd, and then click OK.
        2. Change to the Debugging Tools for Windows folder. To do this, type the following at the command prompt, and then press ENTER:
          cd c:\program files\debugging tools for windows
        3. To load the dump file into a debugger, type one of the following commands, and then press ENTER:
          windbg -y SymbolPath -i ImagePath -z DumpFilePath
          kd -y SymbolPath -i ImagePath -z DumpFilePath

        The following table explains the use of the placeholders that are used in these commands.

        Placeholder Explanation
        SymbolPathEither the local path where the symbol files have been downloaded or the symbol server path, including a cache folder. Because a small memory dump file contains limited information, the actual binary files must be loaded together with the symbols for the dump file to be correctly read.
        ImagePathThe path of these files. The files are contained in the I386 folder on the Windows XP CD-ROM. For example, the path may be C:\Windows\I386.
        DumpFilePathThe path and file name for the dump file that you are examining.



        Sample Commands


        You can use the following sample commands to open the dump file. These commands assume the following:

        • *The contents of the I386 folder on the Windows CD-ROM are copied to the C:\Windows\I386 folder.

        • *Your dump file is named C:\Windows\Minidump\Minidump.dmp.

        Sample 1:

        kd -y srv*c:\symbols*http://msdl.microsoft.com/download/symbols -i c:\windows\i386 -z c:\windows\minidump\minidump.dmp

        Sample 2. If you prefer the graphical version of the debugger instead of the command line version, type the following command instead:

        windbg -y srv*c:\symbols*http://msdl.microsoft.com/download/symbols -i c:\windows\i386 -z c:\windows\minidump\minidump.dmp



        Examine the dump file


        There are several commands that you can use to gather information in the dump file, including the following commands:

        • The !analyze -show command displays the Stop error code and its parameters. The Stop error code is also known as the bug check code.
        • The !analyze -v command displays verbose output.
        • The lm N T command lists the specified loaded modules. The output includes the status and the path of the module.

        Note: The !drivers extension command displays a list of all drivers that are loaded on the destination computer, together with summary information about their memory use. The !drivers extension is obsolete in Windows XP and later. To display information about loaded drivers and other modules, use the lm command. The lm N T command displays information in a format that is similar to the old !drivers extension.

        For help with other commands and for complete command syntax, see the debugging tools Help documentation. The debugging tools Help documentation can be found in the following location:

        C:\Program Files\Debugging Tools for Windows\Debugger.chm

        Note: If you have symbol-related issues, use the Symchk utility to verify that the correct symbols are loaded correctly.

        For additional information about using Symchk, read Use the Microsoft Symbol Server to obtain debug symbol files


        Simplify the commands by using a batch file


        After you identify the command that you must have to load memory dumps, you can create a batch file to examine a dump file.

        For example, create a batch file and name it Dump.bat. Save it in the folder where the debugging tools are installed. Type the following text in the batch file:

        cd "c:\program files\debugging tools for windows"
        kd -y srv*c:\symbols*http://msdl.microsoft.com/download/symbols -i c:\windows\i386 -z %1

        When you want to examine a dump file, type the following command to pass the dump file path to the batch file:

        dump c:\windows\minidump\minidump.dmp

        21 ottobre

        闭包

        JavaScript函数的一个特点是函数可以嵌套。这说明,可以在一个函数中声明另一个函数。考虑以下代码:

         

        这个代码定义了一个名称为parent的函数,它声明了一个局部变量testVariable。在parent函数中,还声明了一个child函数。在这个child函数体中,可以访问在其函数体以外定义的变量testVariable和arg。parent函数的最后一条语句调用了child函数,会在屏幕上的一个消息框中显示这些变量的值。可以用如下方式调用parent函数:
          

        以这种方式调用parent函数会生成图3-1所示的结果。

        这里会发生什么情况?JavaScript函数总是绑定到一个作用域或一个环境(environment)。因此,子函数可以访问父函数的作用域,包括父函数的局部变量和传入父函数的参数。不过真正有用的是,如果让父函数返回其子函数,局部变量在父函数返回后将仍然“存活”。为了说明这种特性的强大作用,下面将parent函数改写如下,如代码清单3-1所示。

         
        图3-1  调用一个父函数,
        该父函数中调用了一个子
        函数

        代码清单3-1  通过返回一个内部函数创建闭包

         

        这一次并不是调用child函数,parent函数将返回child函数。关键是,即使parent函数已经返回,其局部变量仍然存在,可以在child函数中访问。为了验证这一点,必须调用parent函数,然后调用所返回的child函数:
         

        奇怪的是,即使父函数中的变量声明为局部变量,子函数也能访问这些变量。子函数的作用域与其外部函数的局部变量一直是绑定的。只要出现这种情况,你就可以自豪地宣称你创建了一个闭包(closure)。

        修 整

        代码清单3-1中,子函数使用其父函数作用域中定义的两个参数(arg和testVariable)在屏幕上显示了一个消息。不过,调用子函数时可以不带任何参数:这样就把一个需要多个参数的函数转换为一个需要较少参数的函数(在这里就是一个无参数的函数)。这种技术称为修整(currying)。

        要理解闭包并进行处理,刚开始可能会有些困难,因为最常用的那些面向对象语言不支持闭包。不过闭包有一些有意思的应用。例如, 2.3.4节介绍的Function.createDelegate方法就是闭包的一种应用。如果使用C# 2.0实现.NET编程,你可能听说过匿名方法(anonymous methods),这不能称为闭包,不过匿名方法实现了一种与闭包类似的技术。

        说明 如果想了解C#匿名方法的更多内容,可以访问http://msdn2.microsoft.com/en-us/library/ 0yw3tz5k.aspx。