How to scope block of code?

时间:2015-07-28 22:49:26

标签: c# .net enums

If I need to reference a namespace explicitly to avoid conflicts with another namespace, how can that be done when you need to reference it several times within one block of code?

For example:

List<NamespaceA.SomeEnum> myobject = new List<NamespaceA.SomeEnum>()
{
  NamespaceA.SomeEnum.A,
  NamespaceA.SomeEnum.B,
  NamespaceA.SomeEnum.C,
  NamespaceA.SomeEnum.D,
  NamespaceA.SomeEnum.E,
}

Is there a way to shortcut/imply NamespaceA.SomeEnum in the parameter references?

1 个答案:

答案 0 :(得分:5)

You can do

using ASomeEnum = NamespaceA.SomeEnum;

and then

List<ASomeEnum> myobject = new List<ASomeEnum>()
{
    ASomeEnum.A,
    ASomeEnum.B,
    ASomeEnum.C,
    ASomeEnum.D,
    ASomeEnum.E,
}

The using directive needs to be at the top level or within a namespace, but not within a type.


Another option is to move the method containing the offending code block to another file and to make the class partial.

This allows you to use different namespaces in the other file.

相关问题