访问不同命名空间中的枚举
我在VS2005中使用C#。 我有一个类库,其中包含许多不同项目通用的几个枚举。 当访问这些枚举之一时,即使我已经向包含枚举的命名空间声明了“using”指令,我也必须指定枚举的整个命名空间路径。
例如,我有以下枚举:
namespace Company.General.Project1
{
public static class Rainbow
{
[Flags]
public enum Colours
{
Red,
Blue,
Orange
}
}
}
然后在另一个项目中我有:
using Company.General.Project1;
namespace Company.SpecialProject.Processing
{
public class MixingPallette
{
int myValue = Company.General.Project1.Colours.Red;
}
}
即使我有“Using”指令引用包含枚举类的项目,我仍然必须手写枚举。 为什么我不能执行以下操作...
using Company.General.Project1;
namespace Company.SpecialProject.Processing
{
public class MixingPallette
{
int myValue = Colours.Red;
}
}
I'm using C# in VS2005. I have a class library that contains several enums common to a number of different projects. When accessing one of these enums I have to specify the whole namespace path to the enum even though I have declared a 'using' directive to the namespace that contains the enum.
For example I have the following enum:
namespace Company.General.Project1
{
public static class Rainbow
{
[Flags]
public enum Colours
{
Red,
Blue,
Orange
}
}
}
Then in another project I have:
using Company.General.Project1;
namespace Company.SpecialProject.Processing
{
public class MixingPallette
{
int myValue = Company.General.Project1.Colours.Red;
}
}
Even though I have the 'Using' directive referencing the project that contains the class of the enum, I still have to write the enum longhand.
Why can't I do the following...
using Company.General.Project1;
namespace Company.SpecialProject.Processing
{
public class MixingPallette
{
int myValue = Colours.Red;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的枚举不仅仅位于命名空间中 - 它是嵌套类型。 事实上,您的示例“工作”代码不会工作,它必须工作
(您不仅需要包含
Rainbow
部分,而且也没有从枚举到 int 的隐式转换。 )使您的枚举成为顶级类型:
然后您将能够编写:(
请注意,要有效地使用
[Flags]
,您应该显式分配值,例如 1, 2, 4, 8 ...)编辑:我一直假设您确实希望能够使用
Colours.Red
等。您可以使用嵌套类型保留当前结构,然后写:除非您有特殊原因使枚举嵌套,否则我不会。
Your enum isn't just in a namespace - it's a nested type. In fact, your sample "working" code wouldn't work, it would have to be
(Not only do you need to include the
Rainbow
part, but there's also no implicit conversion from an enum to int.)Make your enum a top-level type:
Then you will be able to write:
(Note that to use
[Flags]
effectively, you should be assigning values explicitly, e.g. 1, 2, 4, 8...)EDIT: I've been assuming you really do want to be able to use
Colours.Red
etc. You can keep your current structure, using a nested type, and just write:Unless you have a particular reason to make the enum nested, however, I wouldn't.
您可以将枚举移出静态类 - 它们可以以自己的方式存在。 所以这可行:
但是如果将枚举保留在这个静态类中,那么它只能在该上下文中引用:
You can move your enums out of the static class - they can exist in their own right. So this would work:
But if you keep the enum within this static class, then it can only be referenced in that context: