简体   繁体   English

使用多个命名空间描述一个类

[英]Using Multiple Namespaces to Describe a Class

I am writing code for a game, and wanted to include my main method in two different namespaces so that it could easily access all the classes from both the 'Engine' and 'Core' Namespaces. 我正在为游戏编写代码,并希望将我的main方法包含在两个不同的命名空间中,以便它可以轻松地从“ Engine”和“ Core”命名空间访问所有类。

namespace Engine Core
{
    class ExampleClass
    {
    }
}

Although I just put a space between Engine and Core, I know that this syntax is incorrect, I would like to know how to make a class a member of multiple namespaces. 尽管我只是在Engine和Core之间放置了一个空格,但我知道此语法是不正确的,但我想知道如何使一个类成为多个名称空间的成员。 If this is not possible, is there anything that I could do that would act the same? 如果这不可能,那么我能做些什么来做同样的事情吗? (Classes in neither these two namespaces having to refer to this class by 'Engine.' or 'Core.' (这两个名称空间中的类都不必通过“ Engine。”或“ Core”引用此类。

A class can not belong to two different namespaces. 一个类不能属于两个不同的名称空间。 If you want to refer to a class of the Engine or Core namespaces without explicitly writing the namespace each time you reference a type of those namespaces, just use using at the beginning of the file. 如果要引用Engine或Core命名空间的类,而不必在每次引用这些命名空间的类型时都显式地编写命名空间,则只需在文件开头使用using The using directive allows the use of types in a namespace so that you do not have to qualify the use of a type in that namespace: using指令允许在名称空间中使用类型,因此您不必限定在该名称空间中使用类型:

using Engine;

or 要么

using Core;

Check the documentation: using Directive 检查文档: 使用指令

So you want someone to be able to access ExampleClass by using Engine.ExampleClass and Core.ExampleClass ? 所以,你希望有人能够访问ExampleClass使用Engine.ExampleClassCore.ExampleClass I'm not sure why you would (I'm sure you have your reasons) but two ways to expose something like this are: 我不确定为什么要这么做(我确定你有自己的理由),但是公开这种情况的两种方法是:

namespace Foo
{
    abstract class ExampleClass
    {
         //Only implement the class here
    }
}

namespace Engine
{
    class ExampleClass : Foo.ExampleClass
    {
         //Don't implement anything here (other than constructors to call base constructors)
    }
}

namespace Core
{
    class ExampleClass : Foo.ExampleClass
    {
         //Don't implement anything here (other than constructors to call base constructors)
    }
}

Or you could use namespace aliasing but every cs file using the class would require the alias to be defined. 或者,您可以使用名称空间别名,但是使用该类的每个cs文件都需要定义别名。

using Engine = Core;

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

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