是否可以为 .NET 中的类定义别名?

发布于 2024-10-15 12:52:15 字数 183 浏览 3 评论 0原文

我的一个班级的名称已更改,并且无法更改回来。我必须保持向后兼容性,并且我不想用旧名称编写包装器。 有没有简单的方法来给类 2 命名或给它一个别名?

摘自OP的评论:

不要告诉我使用 using 指令,因为它必须在消费者端完成,而且我不想更改正在使用我的库的项目。

The name of one of my classes was changed and I can't change it back. I have to mantain backwards compatibility and I don't want to write an wrapper with the old name.
Is there any easy way to give a class 2 names or to give it an alias?

Lifted from a comment by the OP:

Don't tell me to use the using directive since it must be done in the consumer side, and I don't want to change the projects that are using my library.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

空宴 2024-10-22 12:52:15

可以说,您最好的选择是使用重构工具(例如 Resharper)来帮助您自动将旧名称转换为新名称。但是,如果由于某种原因这对您来说站不住脚,请在此处有一些替代方案:

如果类型位于不同的程序集中,您可以使用 输入转发器。这些允许您将给定类型的所有引用重定向到程序集...但如果是 IIRC,它们也可以将它们重定向到新名称。

否则,在单个 .cs 源文件中,您可以应用 using 语句:

using OldClassName = SomeNameSpace.NewClassName

但是,这并不能全局解决问题,因为更改许多 .cs 文件以包含此 using 语句可能会变得很痛苦。

另一种选择可能是创建新类型的子类并将其命名

public class OldClassName : NewClassName

为旧名称:这为您提供了新类的别名,但需要您创建重复的公共构造函数并代理对重命名类型的静态方法调用。这远非理想……我一般不推荐这样做。

Arguably, your best option is to use a refactoring tool (like Resharper) to help you automate the conversion from the old name to the new name. However, if this is untenable to you for some reason, here are some alternatives:

If the types are in different assemblies you may be able to use a Type Forwarder. These allow you to redirect all references for a given type to an assembly ... but if IIRC, they can also redirect them to a new name as well.

Otherwise, within a single .cs source file you can apply a using statement:

using OldClassName = SomeNameSpace.NewClassName

This doesn't solve the problem globally, however, as it may become painful to change many .cs files to include this using statement.

Another alternative, may be to create a sub-class of the new type and name it the old name:

public class OldClassName : NewClassName

This gives you aliasing for the new class, but will require that you create duplicate public constructors and proxy static method calls to the renamed type. This is far from ideal ... and I generally don't recommend this.

乞讨 2024-10-22 12:52:15

不幸的是,作为库的作者,唯一的方法是 X 继承 Y,这有一定的注意事项。

有可能但不太可能你可以用 IL 汇编来作弊。

Unfortunately, as the library author, the only way is X inherits Y, which has certain caveats.

It's possible but unlikely you could cheat with IL assembly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文