using 指令到底有什么作用?
在 MSDN 上我可以阅读它的作用,但我想知道它在技术上的作用(告诉编译器在哪里寻找类型..)?我的意思是用作指令。
On MSDN I can read what it does, but I would like to know what it does technically (tells compiler where to look for types..)? I mean using as a directive.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
using
指令的主要功能是使命名空间内的类型无需用户代码限定即可使用。它考虑在引用的程序集和正在编译的项目中定义的命名空间和类型集。以 MyTypes.Dll 中的以下定义为例,
现在考虑从具有不同命名空间的另一个项目引用
MyTypes.dll
。如果没有 using 指令来创建 Class1,我需要限定名称using
指令允许我删除此限定The primary function of the
using
directive is to make types within a namespace available without qualification to the user code. It considers the set of namespaces and types which are defined in referenced assemblies and the project being compiled.Take for example the following definition in MyTypes.Dll
Now consider referencing
MyTypes.dll
from another project with a different namespace. Without a using directive to createClass1
i need to qualify the nameThe
using
directive lets me remove this qualification@JaredPar 的答案是正确的,但我想补充一点,它的工作方式与 Java 中的
import
不太一样。 (如果我对 Java 的import
实际上将其导入到内存中的说法是错误的,请有人纠正我)您需要包含 DLL 或项目引用,以便能够使用
using
但是,直到您实际调用程序集中的方法/属性/某些内容之前,它不会加载到内存中。因此,您可以使用using System.Linq;
但如果您实际上没有使用任何 Linq 方法,则永远不会加载 Linq 程序集。 (我不是 100% 肯定 Linq 位于它自己的物理程序集中,因为命名空间和程序集不是 1:1,但为了举例,我假设它是 1:1)@JaredPar's answer is correct, however I'd like to add that it doesn't quite work the same way as say
import
in Java. (someone correct me if I'm wrong about Java'simport
actually importing it into memory)You need to include either a DLL or project reference in order to even be able to use
using
however it's not loaded into memory until you actually call into a method/property/something in the assembly. So you could haveusing System.Linq;
but if you don't actually use any Linq methods, the Linq assembly is never loaded. (I'm not 100% positive that Linq is in it's own physical assembly since namespaces and assemblies aren't 1:1, but for sake of example I'm assuming it is)using
通知编译器在哪些命名空间中搜索文件中使用但未在文件中定义的名称。using
informs the compiler which namespaces to search for names used in the file but not defined in the file.using 只是告诉编译器转到程序集的配置文件并搜索具有给定名称的特定 DLL,如果找到该 DLL,则将该 DLL 链接到当前项目。 using 只是一个链接操作,使 DLL 在内存中的共享空间中相互通信。
下面这个人说得对
using just tell the compiler to go to the assembly's configuration file and search for a specific DLL with the name given, if the DLL is found then it links that dll into the current project. using is just a link operation to have DLL talk to each other in a shared space in memory.
The guy below here is right