是否有可能定义一个别名一类的.NET? [英] Is it possible to define an alias for a class in .NET?

查看:186
本文介绍了是否有可能定义一个别名一类的.NET?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一个类的名字被更改了,我不能改回来。我有十个分量向后兼容性,我不想写出来与旧名称的包装。 有没有简单的方法来给类2名,或给它一个别名?

这是一个广受评论的OP解禁:

  

不要告诉我使用using指令,因为它必须在消费端来完成,而我不想改变这种状况正在使用我的媒体库中的项目。

解决方案

可以说,最好的选择是使用重构工具(如ReSharper的),以帮助您从旧名称的转换自动为新的名称。 但是,如果这是站不住脚的,以你出于某种原因,这里有一些选择:

如果该类型在不同的组件您可以使用<一个href="http://hoser.lander.ca/2005/09/14/TheWondersOfWhidbeyFactoringFeaturesPartITypeForwarders.aspx"相对=nofollow>类型货代 。这允许你重定向对于一个给定类型的组件的所有引用...但如果​​IIRC,他们也可以将其重定向到一个新的名字。

否则,单一的.cs源文件中,你可以申请一个using语句:

 使用OldClassName = SomeNameSpace.NewClassName
 

这并没有解决问题的全球性,但是,因为它可能成为痛苦的改变许多的.cs文件,包括此使用的语句。

另一种选择,可以创建一个子类的新型并将其命名为旧名称:

 公共类OldClassName:NewClassName
 

这让你别名为新类,但会要求你创建重复的公共构造和代理的静态方法调用重命名的类型。这是很不理想......我一般不建议这样做。

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.

解决方案

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.

这篇关于是否有可能定义一个别名一类的.NET?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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