在两个程序集中同名的类(有意)

编程入门 行业动态 更新时间:2024-10-18 12:23:15
本文介绍了在两个程序集中同名的类(有意)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在迁移一个使用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.

更多推荐

在两个程序集中同名的类(有意)

本文发布于:2023-11-13 14:50:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1584624.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两个   程序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!