2016-08-30 70 views
0

這是好的,我覺得它不是正確的,就像我做一個「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(); 
    } 
+4

你想要一個StackOverflowException?因爲這就是你如何得到StackOverflowException。 – CodeCaster

+1

這很好。它被稱爲遞歸。只要確保在某些時刻c1將會與'null'不同,否則你將得到'StackOverlowException' –

+0

好的謝謝 - 用戶選擇c1而不是代碼,所以應該沒問題。 – gazeranco

回答

5

這將需要一個非常持久的用戶讓這個方法拋出一個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(); 

我不知道浩w TSMUI.Picker.PickObject()可以讓用戶取消選擇一個部分,因爲現在這個方法不會退出,直到用戶選擇一個。我可以想象,他們會後悔在不包含任何組件的工作空間中啓動此操作。

+0

我認爲做...而是更好的方法? – Monah

+0

它不會一直向用戶提示'MessageBox',用戶甚至不能選擇該對象嗎? – Shaharyar

+0

@Shaharyar基於提問的人,PickObject正在等待用戶選擇一個對象 – Monah

相關問題