简体   繁体   English

在命名空间之外使用using语句被识别为另一个命名空间

[英]using statement outside namespace is recognized as a different namespace

I have a few using statements in my class. 我的课堂上有一些using语句。 ReSharper says I need to add another namespace so I let it add it. ReSharper说我需要添加另一个名称空间,所以我让它添加它。 It adds it at the top, outside the namespace declaration and we are all good. 它将其添加到名称空间声明之外的顶部,我们都很好。

But StyleCop says that the usings need to be INSIDE the namespace declaration. 但是StyleCop表示使用需要在名称空间声明的内部。 So I move the using statement inside, but then when I hover over the using statement, it says it's a different namespace. 所以我将using语句移到了里面,但是当我将鼠标悬停在using语句上时,它说这是一个不同的命名空间。 Example below: 下面的例子:

using Owin; // when I hover, it shows up as "Owin", which is correct

namespace MyCompany.Sales.Web
{
    using System.Configuration;
    using System.Web.Http;

After moving it down, it looks like this: 向下移动后,它看起来像这样:

namespace MyCompany.Sales.Web
{
    using System.Configuration;
    using System.Web.Http;
    using Owin; // but when I hover, it shows up as "MyCompany.Owin"

How do I stop visual studio from thinking it needs the "MyCompany" part of the namespace. 如何阻止Visual Studio认为它需要名称空间的“ MyCompany”部分。 Keep in mind, there IS a namespace called "MyCompany.Owin", but I do NOT have a reference to it in the project. 请记住,有一个名为“ MyCompany.Owin”的名称空间,但是我在项目中没有对其的引用。

I don't know why this happens or how to otherwise avoid it but one way would be to instruct the C# compiler to start at the global namespace before trying to resolve the name. 我不知道为什么会这样或如何避免这种情况,但是一种方法是在尝试解析名称之前,指示C#编译器从全局名称空间启动。

You would simply prefix the namespace with the global:: modifier (yes, that's two colons in there), like so: 您只需在名称空间前面加上global::修饰符(是的,那里是两个冒号),就像这样:

using global::Owin;

You can use this "trick" on types as well, assuming you have a close-by type that has a name that matches something else and no matter which combination of namespaces and whatnot the compiler still thinks it should use your closer type (usually this suggests that you have a bad name but that's a different issue): 您也可以在类型上使用此“技巧”,假设您有一个名称与其他名称匹配的close-by类型,无论命名空间的组合是什么,编译器仍然认为它应使用您的closer类型(通常是建议您使用一个不好的名字,但这是另一个问题):

using (var stream = new global::System.IO.FileStream(...))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM