基于可能属于多种不同类型之一的对象调用重载方法的理想方法是什么?
对于我的 WPF 视图,我有几个实现单个界面以用于显示目的的对象。当选择一个时,我想根据视图上选择的类型和选项调用某种方法。我已经为每种类型的对象提供了可用的重载。我尝试使用通用方法,但事实证明这些对象差异太大而无法使用。
为了可维护性,我试图避免控制与大型 if 语句耦合。
我使用单一接口是否出错了,或者是否有一种有趣的可维护方法来执行此操作?
我有一个包含 IDisplayableObject 集合的数据网格。
public interface IDisplayableObject
{
string Name { get; set; }
string ID { get; set; }
}
现在,我作为第一个答案。
public void ExportDashed(string path, IDisplayableObject folder)
{
if (folder is TestFolder)
{
IndentationTraverse(folder as TestFolder);
}
else if (folder is UserStory)
{
IndentationTraverse(folder as UserStory);
}
_excelManipulator.Save(path);
}
我想避免 if 语句。对于这种情况,我通常使用映射到操作的字典,但我还有另一种方法,
public void ExportShiftingColumns(string path, IDisplayableObject folder)
{
if (folder is TestFolder)
{
ColumnShiftTraverse(folder as TestFolder);
}
else if (folder is UserStory)
{
ColumnShiftTraverse(folder as UserStory);
}
_excelManipulator.Save(path);
}
所以,我需要制作操作,导出虚线或导出移位列,然后我需要决定导出哪种类型。
从代码中可以看出,重复并不是一件好事,我想尽可能避免它。对于这个应用程序来说,这并不是什么大不了的事,更多的是为了我个人的学习。
For my WPF view, I have several objects that implement a single interface for display purposes. When one is selected, I want to call a certain method based on the type and options chosen on the view. I already have Overloads available for each type of object. I attempted using a generic method, but it proved that the objects were too different to be useable.
I am trying to avoid control coupling with large if statements for maintainability purposed.
Did I go wrong by using the singular interface, or is there an interesting maintainable way of doing this?
I have a datagrid that contains a collection of IDisplayableObject.
public interface IDisplayableObject
{
string Name { get; set; }
string ID { get; set; }
}
Right now, I cast as the first answer.
public void ExportDashed(string path, IDisplayableObject folder)
{
if (folder is TestFolder)
{
IndentationTraverse(folder as TestFolder);
}
else if (folder is UserStory)
{
IndentationTraverse(folder as UserStory);
}
_excelManipulator.Save(path);
}
I want to avoid the if statements. For this case, I usually use a dictionary mapped to an Action, but I also have another method of
public void ExportShiftingColumns(string path, IDisplayableObject folder)
{
if (folder is TestFolder)
{
ColumnShiftTraverse(folder as TestFolder);
}
else if (folder is UserStory)
{
ColumnShiftTraverse(folder as UserStory);
}
_excelManipulator.Save(path);
}
So, I need to make the action, Export Dashed or Export Shifting Columns, then I need to decide which type to export.
You can see from the code, duplication is not a good thing and I want to avoid it as much as possible. For this application, it is not that big of a deal but more for my personal learning.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许不是最优雅的解决方案,但尝试
等等......
Maybe not the most elegant solution, but try
and so on...