【问题标题】:Looking for the wrong namespace?寻找错误的命名空间?
【发布时间】:2014-12-16 22:40:04
【问题描述】:

我遇到了一些命名空间问题,这让我感到困惑。

在下面的代码中,System.IO 和 System.Reflection 试图引用 abc.System 而不是使用我在顶部声明的 System 命名空间。这是为什么呢?

using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace abc.Data
{
public sealed class Access
{
    public static void Open(string dbPath)
    {
         // error here referencing abc.System in System.IO, and System.Reflection.

         string appPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);         }
}

然后我在一个单独的文件中有另一个命名空间,如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace abc.System
{
     public static class DateTimeExtensions
     {
    // Implemented from
    // http://stackoverflow.com/questions/38039/how-can-i-get-the-datetime-for-the-start-of-the-week
    public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
    {
        int diff = dt.DayOfWeek - startOfWeek;
        if (diff < 0)
        {
            diff += 7;
        }

        return dt.AddDays(-1 * diff).Date;
    }

    public static DateTime EndOfWeek(this DateTime dt, DayOfWeek startOfWeek)
    {
        int diff = dt.DayOfWeek - startOfWeek;
        if (diff < 0)
        {
            diff += 7;
        }

        return dt.AddDays(diff).Date;
    }
}
}

【问题讨论】:

标签: c# .net


【解决方案1】:

由于存在命名空间冲突,您需要使用 global 关键字来明确您要访问的内容。

string appPath = global::System.IO.Path.GetDirectoryName(global::System.Reflection.Assembly.GetExecutingAssembly().Location); 

或者,如果可以的话,改变你的命名空间,因为那会很快变得很烦人!

【讨论】:

  • 但是为什么会出现命名空间冲突呢?为什么不将 System 称为 System 命名空间,而将 abc.System 称为 abc.System 命名空间?为什么要提到 System,是 abc.System?
  • 因为本地命名空间总是优先。因此,当您键入 System 时,它会在 abc.Data (您当前的命名空间)中查找并没有找到任何内容,然后备份一个级别以查看 abc 并且由于您显示的其他类,它会找到一个命名空间在命名空间 abc. 中调用 System 所以它使用它,这不是你的意图。
  • FWIW 对于所有语言,我都避免使用疯狂的关键字(尽管这在 SQL 中更成问题)
  • 我明白了。那么当人们遇到这种冲突时该怎么办,因为我想这种情况经常发生并且使用替代语法并不漂亮?
  • 有点像@alykins 所说的 - 避免使用关键字(或关键字之类的东西 - 例如默认的命名空间集)。拥有自己的系统命名空间(特别是因为它不是顶级的)将是一个问题。我只是避免这种情况。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-25
  • 1970-01-01
  • 1970-01-01
  • 2013-06-17
  • 2018-10-03
  • 2017-02-15
相关资源
最近更新 更多