启用对包含在当前脚本或外部库中的命名空间的访问。
import namespace
- namespace
必选。要导入的命名空间的名称。
import 语句在名称提供为 namespace 的全局对象上创建属性并将其初始化,以包含对应于所导入命名空间的对象。任何使用 import 语句创建的属性都不能赋给其他对象、删除或枚举。所有 import 语句都在脚本开始时执行。
import 语句为您的脚本提供命名空间。命名空间可以在脚本中使用 package 语句来定义,或者外部程序集可能会提供命名空间。如果没有在脚本中找到命名空间,JScript 将在指定的程序集目录中搜索与命名空间的名称匹配的程序集,除非您正在编译程序并关闭 /autoref 选项。例如,如果导入命名空间 Acme.Widget.Sprocket 但该命名空间没有在当前脚本中定义,JScript 将在下列程序集中搜索命名空间:
-
Acme.Widget.Sprocket.dll
-
Acme.Widget.dll
-
Acme.dll
您可以显式地指定要包括的程序集的名称。如果关闭 /autoref 选项或命名空间的名称与程序集名称不匹配,则必须进行这种显式指定。命令行编译器使用 /reference 选项来指定程序集名称,而 ASP.NET 使用 @ Import 和 @ Assembly 指令来完成此任务。例如,若要显式地包含程序集 mydll.dll,请从命令行键入
jsc /reference:mydll.dll myprogram.js
若要包括 ASP.NET 页的程序集,需要使用
<%@ Import namespace = "mydll" %> <%@ Assembly name = "mydll" %>
当在代码中引用一个类时,编译器首先在局部范围内搜索该类。如果编译器没有找到匹配类,编译器将按照导入顺序搜索每个命名空间中的类,并在找到匹配项时停止。您可以使用类的完全限定名来确定类所派生自的命名空间。
JScript 不会自动导入嵌套命名空间;每个命名空间必须使用完全限定命名空间来导入。例如,若要从一个名为 Outer 的命名空间和一个名为 Outer.Inner 的嵌套命名空间中访问类,则必须导入这两个命名空间。
示例下面的示例定义了三个简单的包,并将命名空间导入到脚本中。通常,每个包都位于一个单独的程序集中以便维护和分发包的内容。
// Create a simple package containing a class with a single field (Hello). package Deutschland { class Greeting { static var Hello : String = "Guten tag!"; } }; // Create another simple package containing two classes. // The class Greeting has the field Hello. // The class Units has the field distance. package France { public class Greeting { static var Hello : String = "Bonjour!"; } public class Units { static var distance : String = "meter"; } }; // Use another package for more specific information. package France.Paris { public class Landmark { static var Tower : String = "Eiffel Tower"; } }; // Declare a local class that shadows the imported classes. class Greeting { static var Hello : String = "Greetings!"; } // Import the Deutschland, France, and France.Paris packages. import Deutschland; import France; import France.Paris; // Access the package members with fully qualified names. print(Greeting.Hello); print(France.Greeting.Hello); print(Deutschland.Greeting.Hello); print(France.Paris.Landmark.Tower); // The Units class is not shadowed, so it can be accessed with or without a fully qualified name. print(Units.distance); print(France.Units.distance);
该脚本的输出为:
Greetings! Bonjour! Guten tag! Eiffel Tower meter meter要求请参见
参考
package 语句/autoref
/lib
@ Assembly
@ Import