简体   繁体   中英

How to alias a enum name to override local namespace enum with the same name?

I'm doing a major refactor where I am replacing an enum, called "Main.TestEnum", with an enum from another namespace, called "Library.TestEnum". I need to temporarily keep both enums for now and later I can replace every instance with "Library.TestEnum".

I was hoping I could toggle back and forth between the enums with "using" aliases:

using TestEnum = Library.TestEnum; //Create the alias
namespace Main {
class Program
    {
        static void Main(string[] args)
        {
            TestEnum testEnum = TestEnum.Uninitialized;
            Console.WriteLine(testEnum.GetType()); //Always outputs Main.TestEnum!
        }
    }
}

In spite of the alias, the unqualified name "TestEnum" always refers to "Main.TestEnum" and never "Library.TestEnum" for code in the "Main" namespace. Aliases appear to NOT work if there's something else defined with that name in your current namespace. :(

I can go through all of my code and do a search and replace of "TestEnum" with "Library.TestEnum" but this seems annoying, makes the code harder to read, and makes me have to touch every file that uses the enum (there's a lot of code using it.)

Does anyone know a work around for this? Why does the C# compiler not support this? Isn't every non-qualified name really an alias and shouldn't I be able to override the aliases for names in the current namespace?

To fix this relatively easily, I simply moved "Main.TestEnum" to be "SomeUnusedNameSpace.TestEnum". This moved both versions of TestEnum out of the "Main" namespace, meaning that any references to "TestEnum" had to be explicit because the compiler couldn't auto default to the version in the current namespace. I had to add "using TestEnum = Library.TestEnum;" to a fairly large number of files to fix compiler errors, but it was a single line added instead of giant rename, which made merges easier.

I still don't know if this is a compiler "bug" or simply a request I should make to the compiler team, but I feel that "using" aliases SHOULD override symbols in the current namespace or at the very least throw a compiler error if the alias clashes with a current symbol name or at least a warning that the alias will not do anything.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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