How to get the namespace alias operator :: to work under C#?

岁酱吖の 提交于 2019-11-30 22:06:45

问题


I've come up against the unlikely scenario when I reference two external assemblies that both have the same namespace and type names. When I try to use the type, the compiler throws an error that it cannot resolve which one I want to use.

I see that C# offers a mechanism to use aliases for references. You can even specify these aliases via the Property window of a reference in Visual Studio 2008. How do I use this alias in my code? As I understand, I should be using the :: operator, but it fails with the following error:

CS0432 - Alias not found

The usual . operator fails as well.

In the output window I see that the compiler gets the alias passed correctly in its command line.

Any pointers on what I may be able to try next are greatly appreciated.


回答1:


extern alias alias1;
using alias1::Namespace;



回答2:


Try this:

extern alias asm1;
extern alias asm2;

namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            asm1.MyNs.MyClass mc1 = null;
            asm2.MyNs.MyClass mc2 = null;
        }
    }
}

And add global,asm1 to the project reference for assembly1 and global,asm2 for assembly2




回答3:


I think you need to use an extern alias. Anson Horton has a good blog on this problem and how to use extern alias to fix it.




回答4:


When you reference some assembly in project it has default alias "global". When you add another alias for that assembly, e.g. "global, AssemblyA", you will reference it like this:

using SomeTypeAlias = AssemblyA::Company.Product.SomeType;

or:

void SomeMethod(AssemblyA::Company.Product.SomeType someType) { ... }


来源:https://stackoverflow.com/questions/619104/how-to-get-the-namespace-alias-operator-to-work-under-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!