在遗留代码中支持新属性的最佳方式是什么
我有一个关于遗留的架构问题。 例如,我有一个在项目中随处使用的类。项目没有任何单元测试,
public class LegacyObject
{
public Dictionary<string, string[]> MyLegacyProperty { get;set;}
}
我需要将字典类型更改为其他类型,例如 IEnumerable
。
更改它的最佳方法是什么,并且不要更改字典 MyLegacyProperty 使用的代码部分。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,
Dictionary
确实实现了IEnumerable>
,因此任何想要使用 IEnumerable 的东西都可以引用 Dictionary 属性,并且它会起作用的。既然您想要进行更改,我假设您想做一些字典不允许的事情,也许是重复的键。如果替换属性可以转换为字典,我会做这样的事情。将旧属性放在新属性旁边,并处理旧属性的 getter 和 setter 中的转换。请注意,如果 MyLegacyProperty 的用例是检索它、修改它而不是设置它,则此模式将失败;在这种情况下,你需要做一些类似于 ObservableCollection 的事情。 (有 ObservableDictionary 吗?)
如果替换属性无法转换为字典,那么您正在谈论对类的外部接口进行真正的更改。我不认为有什么可以替代硬着头皮做出改变而没有向后兼容性。我可以给您的唯一提示是使新属性具有与旧属性不同的名称:您将能够使用“在文件中查找”来查找需要更改的代码,这将使编译器错误你得到的信息是清晰明确的。
Well,
Dictionary<T,U>
does implementIEnumerable<KeyValuePair<T,U>>
, so anything that wants to use the IEnumerable could reference the Dictionary property and it would work. Since you want to make that change, I'm assuming you want to do something that a Dictionary doesn't allow, duplicate keys, perhaps.If the replacement property can be converted to a Dictionary, I'd do something like this. Have you old property sitting next to your new property, and deal with conversions in the old property's getter and setter. Note that this pattern will fail if the use case for MyLegacyProperty is to retrieve it, modify it, and not set it back; you'll need to do something akin to ObservableCollection in that case. (Is there an ObservableDictionary?)
If the replacement property can't be converted to a Dictionary, then you're talking about making a real change to the external interface of your class. I don't believe there's any substitute for biting the bullet, and making the change with no backward compatibility. The only tip I can give you is to make the new property have a different name from the old one: You'll be able to use Find In Files to find the code you need to change, and it will make it so the compiler errors you get are clear and unambiguous.
如果您可以使用新名称创建新属性,则可以将旧属性标记为
[已过时]
,并慢慢迁移代码库以使用新属性,直到没有对旧属性的引用一个,你可以删除它。如果必须使用旧的属性名称,并且该属性仅在 Visual Studio 中的一个解决方案中使用,则可以使用重命名重构并将名称更改为类似
MyLegacyProperty_Old
的名称,然后创建新属性与旧名称。无论哪种情况,为您的班级编写一些单元测试都是一个好主意。
If you can create a new property with a new name, you could mark the old one as
[Obsolete]
and slowly migrate your code base to use the new property, until there're no references to the old one and you can delete it.If you must use the old property name, and if the property is only used within one solution in Visual Studio, you can use the renaming refactoring and change the name to something like
MyLegacyProperty_Old
and then create the new property with the old name.In either case, it's a good idea to write some unit tests for your class.