没有“使用” ASP.NET 生成的代码中的引用

发布于 2024-12-03 08:52:39 字数 278 浏览 0 评论 0原文

当我查看 aspx 页面的生成代码时,有一件事让我震惊。每次都会打印每个类引用,而不是应用代码文件顶部的“using”方法。
这样做有理由吗?
如果这两种方法没有区别,那么为什么不使用“using”来简化呢?

System.Data.DataSet theSet = new DataSet();

using System.Data;  
DataSet theSet = new DataSet();

When I looked at the generated code of an aspx page, one thing struck me. Every class reference is printed every time instead of applying the "using" method at the top of the code file.
Is there a reason for doing this?
If there's no difference in the two methods then why not use "using" for simplicity?

System.Data.DataSet theSet = new DataSet();

vs

using System.Data;  
DataSet theSet = new DataSet();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

幻梦 2024-12-10 08:52:39

因为对于生成的代码来说,阅读的简单性并不是优先考虑的。

然而,编写的简单性是一个问题:如果类型始终使用其完全限定名称来指定,则名称冲突的可能性就会降低。想象一下,您有两个提供 TextBox 控件的库,并且将它们都添加到 Web 表单中。

// no problem
System.Web.UI.WebControls.TextBox myDefaultTextBox = new System.Web.UI.WebControls.TextBox();
CustomLibrary.TextBox theOtherTextBox = new CustomLibrary.TextBox();

相比于

using System.Web.UI.WebControls;  
using CustomLibrary;  

// won't compile, would need special treatment by the code generator
TextBox myDefaultTextBox = new TextBox();
TextBox theOtherTextBox = new TextBox();

Because for generated code, simplicity of reading is not a priority.

Simplicity of writing is an issue, however: If types are always specified with their fully qualified name, the likelihood of a name conflict decreases. Imagine that you have two libraries that provide TextBox controls, and you add both of them to your web form.

// no problem
System.Web.UI.WebControls.TextBox myDefaultTextBox = new System.Web.UI.WebControls.TextBox();
CustomLibrary.TextBox theOtherTextBox = new CustomLibrary.TextBox();

as compared to

using System.Web.UI.WebControls;  
using CustomLibrary;  

// won't compile, would need special treatment by the code generator
TextBox myDefaultTextBox = new TextBox();
TextBox theOtherTextBox = new TextBox();
心凉怎暖 2024-12-10 08:52:39

可能是为了帮助避免类型歧义。

更新:Heinzi 的描述更加优雅。

Probably to help avoid type ambiguities.

Update: More elegantly described by Heinzi.

壹場煙雨 2024-12-10 08:52:39

没有理由完全限定类型名称,除非为了清晰起见您遵循某种编码标准。

There is no reason to fully qualify the type name like that unless there is some kind of coding standard you are following for clarity.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文