在两个程序集中同名的类(有意) [英] Class with same name in two assemblies (intentionally)

查看:247
本文介绍了在两个程序集中同名的类(有意)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在迁移一个使用C ++编写的库,并且有一个C#包装器。 C#包装器( LibWrapper )有一组具有命名空间的类,如:

  namespace MyNamespace 
class MyClass
class MyOtherClass

LibraryCS 包含与 LibWrapper (每个用户要求)相同的命名空间和类名,所以我也有:

 命名空间MyNamespace 
class MyClass
class MyOtherClass

现在迁移完成了,我正在创建一个测试,比较使用这两个库的结果,以验证迁移。但是,当我尝试引用 MyNamespace.MyClass 我得到一个编译器错误(预期!)说MyNamespace.MyClass在LibWrapper和LibraryCS中定义。



这个问题是否有任何伎俩,这将允许我在同一个客户端代码中使用两个完全相同的名称但是来自不同程序集的类?

$ b $



将迁移的命名空间重命名为 MyNamespace2

code>当然会工作,但我们被要求不这样做,以保持客户端代码更容易迁移。

解决方案

您可以使用外部别名 a>到来自不同程序集的具有相同完全限定名称的引用类型。选择对LibraryCS的引用,并将属性页中的别名从global更新为LibraryCS,并将 extern alias LibraryCS; 添加到源文件的顶部,然后您可以使用 LibraryCS :: MyNamespace.MyClass 来引用LibraryCS中的类。您可以使用 MyNamespace.MyClass global :: MyNamespace.MyClass 来引用LibWrapper中的类,使用该引用的别名。


I'm in the process of migrating a library that is written in C++ and has a C# wrapper. The C# wrapper (LibWrapper) has a set of classes with namespaces, like:

namespace MyNamespace
   class MyClass
   class MyOtherClass

My new library, LibraryCS contains the same namespaces and class names as LibWrapper (per user requirement), so I also have:

namespace MyNamespace
   class MyClass
   class MyOtherClass

Now that the migration is done, I'm in the process of creating a test that compares the results of using both libraries, to validate the migration. However, when I try to reference MyNamespace.MyClass I get a compiler error (expectedly!) that says "MyNamespace.MyClass is defined in both LibWrapper and LibraryCS".

Is there any trick around this issue, that will allow me to use two classes with the exact same name but from different assemblies in the same client code?

Alternatively, is there any other way to test this?

Renaming the migrated namespace to something like MyNamespace2 will of course work, but we were asked not to do it, in order to keep the client code easier to migrate.

解决方案

You can use an extern alias to reference types with the same fully qualified name from different assemblies. Select the reference to LibraryCS and update Aliases in the properties page from "global" to "LibraryCS", and add extern alias LibraryCS; to the top of your source file, and then you can use LibraryCS::MyNamespace.MyClass to refer to the class in LibraryCS. You can use MyNamespace.MyClass or global::MyNamespace.MyClass to refer to the class in LibWrapper, or you can use an alias for that reference as well.

这篇关于在两个程序集中同名的类(有意)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆