开发者

c# class - make function or method call and pass control

开发者 https://www.devze.com 2023-01-25 12:23 出处:网络
I\'m not sure if my title is really correct.I\'ve looked 开发者_如何转开发around and searched but not found anything so please forgive me if my problem has been answered already.

I'm not sure if my title is really correct. I've looked 开发者_如何转开发around and searched but not found anything so please forgive me if my problem has been answered already.

What I would like to do is call a function but not have to come back to the calling line of code. e.g

public static void temp(obj) {
   switch (obj.id) {
     case "1" :
       if(blah) {
         obj.id = "2";
         temp(obj);
       }
       break;
     case "2" :
       obj.response = "done";
       break;
   }
}

so basically I dont want to eventually come back to my temp(obj) in the first case and fully pass control. Does this make sense, is it even possible and my architecture is all wrong?

Thank you for your time.


Let me see if I understand the question:

You've got a function Foo(), which calls function Bar(). (I wanted to remove the recursion you had in your example for simplicity, please correct me if that was important.) When function Bar() returns, you want control to pass not back to Foo(), but to Foo's caller?

This is probably possible in lower-level languages, like C, by hacking the stack and not placing Foo()'s return address there, so that when Bar() tried to return, it would jump to Foo's caller instead.

However, in C#, no. The call stack is a stack, and control will pass back in order. The only thing you can do would be to put a return statement after each call to Bar().

Edit:

"recursive calls without them being recursive"

How about this:

bool doItAgain = true;
while(doItAgain)
{
    doItAgain = false;

    // process, with your switch statement or whatever.

    if(...)
    {
        doItAgain = true;
        continue; // if necessary, skip any code after this statement. May not be necessary if you have things set up right.
    }
}


If this were C++, you could eliminate the break and let the case "1" fall through, but this is not allowed in C# switch statements.

public static void temp(obj) {
   if (obj.id == "1") {
      obj.id = "2";
      temp(obj);
   }

   if (obj.id == "2")
       obj.response = "done";
}

Do you need the recursive call? This code retains your recursive call and sets obj.response to "done" after changing obj.id to "2". However, obj.response is set twice because of the recursive call. What are you trying to do?


I'm not sure what you exactly intend, but it sounds like a callback to me. Here is one possible example:

void DoSome()
{
    ThreadPool.QueueUserWorkItem(new WaitCallback(delegate { RunMe(); ReturnTo(); }));
}

void RunMe() { }

void ReturnTo() { }

You start in DoSome() and continue, when RunMe is finished ReturnMe is called.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号