是否可以从方法内部再次调用该方法
本文关键字:方法 调用 内部 是否 | 更新日期: 2023-09-27 18:04:53
这样可以吗,我觉得这样不对,就像我在做一个"GOTO",这样可以吗?
private void myCopySpecial()
{
TSMUI.Picker myPicker1 = new TSMUI.Picker();
Component c1 = myPicker1.PickObject(TSMUI.Picker.PickObjectEnum.PICK_ONE_OBJECT) as Component;
TSMUI.Picker myPicker2 = new TSMUI.Picker();
Beam fromBeam = myPicker2.PickObject(TSMUI.Picker.PickObjectEnum.PICK_ONE_PART) as Beam;
if (c1 == null)
{
MessageBox.Show("That's not a component? Try again.");
//User selected something other than a component, start again.
myCopySpecial();
}
让这个方法抛出StackOverflowException需要非常持久的用户,但是这种可能性是存在的。这是因为这种设计引入了一种你作为程序员无法控制的递归。
一个简单的while循环就足够了:
private void PickComponent()
{
Component c1 = null;
while (c1 == null)
{
TSMUI.Picker myPicker1 = new TSMUI.Picker();
c1 = myPicker1.PickObject(TSMUI.Picker.PickObjectEnum.PICK_ONE_OBJECT) as Component;
if (c1 == null)
{
MessageBox.Show("Please select a component.");
}
}
}
或者将其重构为一个方法,该方法实际选择组件,并在用户没有选择组件时继续提示用户:
private Component PickObjectAsComponent()
{
Component pickedComponent;
do
{
TSMUI.Picker myPicker1 = new TSMUI.Picker();
pickedComponent = myPicker1.PickObject(TSMUI.Picker.PickObjectEnum.PICK_ONE_OBJECT) as Component;
if (pickedComponent == null)
{
MessageBox.Show("Please select a component.");
}
} (while pickedComponent == null)
return pickedComponent;
}
然后从你的代码中,你可以简单地调用这个方法:
Component pickedComponent = PickObjectAsComponent();
我不知道TSMUI.Picker.PickObject()
怎么能让用户取消选择一个零件,因为现在这个方法不会退出,直到用户选择一个。我可以想象他们会后悔在一个不包含任何组件的工作区中开始这个操作。