【问题标题】:How to define using statements in web.config?如何在 web.config 中定义 using 语句?
【发布时间】:2011-02-08 19:11:15
【问题描述】:

我在我的 asp.net 项目中使用 MySql。但我不想键入每个“使用 MySql.Data.MySqlClient;”每个 aspx.cs/aspx.vb 文件中的语句。如何在 web.config 文件中定义这些行?

我已经定义了一些命名空间,如下所示,但这仅适用于 aspx 页面:

<?xml version="1.0"?>
<configuration>
    <system.web>
        <compilation debug="false" targetFramework="4.0"/>
        <pages>
            <namespaces>
                <add namespace="System.Web.Configuration"/>
                <add namespace="MySql.Data"/>
                <add namespace="MySql.Data.MySqlClient"/>
            </namespaces>
        </pages>
    </system.web>
</configuration>

相关问题:Define common namespaces for code pages in Web.Config

【问题讨论】:

    标签: asp.net .net-4.0 namespaces web-config asp.net-4.0


    【解决方案1】:

    无法为代码隐藏设置全局使用。您必须将 usings 放在代码文件中。

    【讨论】:

    • +1。 using 是源代码中的一条语句,由 C# 编译器处理。 web.config 用于 Web 服务器配置
    • 而aspx页面是由...编译的?这对我来说不合逻辑:)
    • .aspx page - 只是带有服务器端代码的标记 - 它们也由 Web 服务器处理。 .aspx.cs 是源文件。您甚至可以将其命名为 1.cs - 只是不要忘记在页面声明中指定它。
    • P.S.请在尼克之前使用符号@,即@abatishchev,所以很容易找到您对我的评论。谢谢! :)
    • @abatishchev 好的。我google了一整天,但没有解决方案。可能没有解决办法。也许这就是为什么每个代码隐藏页面都包含 using System; :(
    【解决方案2】:

    是的,你可以。如果您打开 %Program Files%\Microsoft Visual Studio 8\Common7\IDE\ItemTemplates\CSharp\1033\Class.zip, 或者:%Program Files%\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033

    您可以修改其中用于生成所有新 C# 源文件的 class.cs 文件 - 它看起来像这样:

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace $rootnamespace$
    {
        class $safeitemrootname$
        {
        }
    }
    

    此外,还有一个名为 Class.vstemplate 的文件。打开它,您可以编辑以下内容:

    <Reference>
        <Assembly>System</Assembly>
            </Reference>
            <Reference>
                <Assembly>System.Data</Assembly>
            </Reference>
            <Reference>
                <Assembly>System.Xml</Assembly>
            </Reference>
        </References>
    

    【讨论】:

    • 对不起,我无法解释清楚。只是我不想在那里看到该代码:)。这个解决方案也不好,因为在一些项目中我在一些 SQL 服务或访问中使用 MySQL...
    • 在这种情况下,我认为您最好将@Tom 的答案标记为正确,因为它无法完成。
    • 如果您担心管理“使用”,我建议您购买 Resharper 插件。它有一个出色的模板机制,如果你想这样做,你可以使用它来生成用于不同目的的“使用”。它具有清理功能,可以删除未使用的“使用”并将它们按逻辑顺序排序,以保持代码整洁。它还有一个功能,可以在您键入代码时检测丢失的“使用”,并提示您查看是否希望它为您添加“使用”。它也做得更多。强烈推荐。
    【解决方案3】:

    只需将您的 using 块包装在 #region 中并折叠它。不用担心有多少用途。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-25
      • 2013-09-06
      • 2019-02-05
      • 2013-12-01
      • 2014-01-31
      • 1970-01-01
      • 1970-01-01
      • 2010-11-22
      相关资源
      最近更新 更多