简体   繁体   English

从CLI / C ++类在C#中使用名称空间

[英]using namespace in C# from CLI/C++ class

This might be a C#-noob question... 这可能是C#-noob问题...

Assume I have the following CLI/C++ header: 假设我具有以下CLI / C ++标头:

namespace DotNet {
  namespace V1 {
    namespace X {


      public ref class AClass {
      public:

        AClass() {}
        void foo() {}

        static void bar() {}
      };
    }
  }

}

Then from C# I do the following: 然后从C#中执行以下操作:

using DotNet;
V1.X.AClass a = new V1.X.AClass();

I get: 我得到:

Program.cs(18,7): error CS0246: The type or namespace name 'V1' could not be found (are you missing a using directive or an assembly reference?) Program.cs(18,7):错误CS0246:找不到类型或名称空间名称“ V1”(您是否缺少using指令或程序集引用?)

Same with: 与:

 using DotNet.V1;
 X.AClass a = new X.AClass();

Program.cs(18,7): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) Program.cs(18,7):错误CS0246:找不到类型或名称空间名称“ X”(是否缺少using指令或程序集引用?)

What works is: 起作用的是:

 DotNet.V1.X.AClass a = new DotNet.V1.X.AClass();

Or 要么

 using DotNet.V1.X;
 AClass a = new AClass();

So either I have to use the full namespace path, or I have to open all of the path to access the class. 因此,要么我必须使用完整的名称空间路径,要么必须打开所有路径以访问该类。 Is there anything I can do about this? 有什么我可以做的吗? I would like to be able to open only a part of it. 我只希望打开其中的一部分。

So either I have to use the full namespace path, or I have to open all of the path to access the class. 因此,要么我必须使用完整的名称空间路径,要么必须打开所有路径以访问该类。

Yes. 是。

Is there anything I can do about this? 有什么我可以做的吗?

Not that I'm aware of. 不是我知道的。 Why would you not just want a using directive for the whole namespace? 为什么你会不会只想使用指令整个命名空间? Isn't that the simplest approach? 这不是最简单的方法吗?

Note that this has nothing to do with C++/CLI. 请注意,这与C ++ / CLI没有关系。 The same is true whatever the source language is - so you can see it with C# as well: 不论源语言是什么,都一样-因此您也可以使用C#进行查看:

namespace DotNet.V1.X
{
    public class AClass {}
}

As Jon Skeet stated you have to include the full namespace in either the using statement or each time you reference it in code. 正如Jon Skeet所说,您必须在using语句中或每次在代码中引用它时都包含完整的名称空间。 I recommend just placing the full namespace in the using statement. 我建议仅将完整的名称空间放在using语句中。

You can, however, achieve that syntax with a using alias, but it does not add anything of value outside of syntax. 但是,您可以using别名实现该语法,但不会在语法之外添加任何有价值的内容。

using V1 = DotNet.V1;

...

   V1.X.AClass a = new V1.X.AClass();

Also if you are using C# version 3.0 or higher the var keyword will only require you type out the full namespace on the right side of the assignment. 同样,如果您使用的是C#3.0版或更高版本,则var关键字将只需要您在分配的右侧键入完整的名称空间。

var a = new DotNet.V1.X.AClass();

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

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