說我有如下的作品的東西的方法答:
在C#中返回一個值之前執行的方法
methodA() {
while(some condition) {
do computation...
if(something 1) {
do computation...
if(some condition) {
return result;
}
}
else if(something 2) {
do computation...
if(some other condition) {
return result;
}
}
}
return something;
}
這種方法既可在while循環的條件下返回,或一段時間後,循環。
現在說我想要一些其他方法,稱之爲methodB()
,在返回之前被激活。我可以這樣做:
methodA() {
while(some condition) {
do computation...
if(something 1) {
...
if(some condition) {
methodB();
return result1;
}
else if(something 2) {
...
if(some condition) {
methodB();
return result2;
}
}
}
}
methodB();
return result3;
}
但我覺得它很醜。有沒有更好的方式在C#中做這樣的事情?
呼叫'的methodB()'之前,你的if語句? – maccettura
請參閱http://stackoverflow.com/questions/36707/should-a-function-have-only-one-return-statement –
聽起來像[XY問題](https://meta.stackexchange.com/a/ 66378/246449),你想用這個做什麼?也許還有其他方法可以解決你的問題,但是我們不知道這裏的實際目標是什麼。 –