What is the use of labels in C#?

前端 未结 13 2165
面向向阳花
面向向阳花 2020-12-17 20:18

Labels and GOTOs are considered bad practice and as far as I know there is no reason to use it in C#.

What is the use of labels in C#?

相关标签:
13条回答
  • 2020-12-17 20:56

    Just because they are a disreputable practice, doesn't mean to should close off any possibility of using them. While they may never actually be required, they are occasionally the best way to go.

    0 讨论(0)
  • 2020-12-17 21:01

    The use of labels is to support goto. Bad as goto may be, if you have goto in the language, then you need labels. Without goto, labels are indeed useless in C#.

    0 讨论(0)
  • 2020-12-17 21:02

    Sometimes a well placed 'goto' is more elegant/readable than other techniques. Putting 'goto's around when they're not needed is certainly a bad practice. As always, each situation should be judged carefully.

    For example, 'goto's can be nice when your function needs to do cleanups in case it fails. You place a label at the end of the function, where you do your cleanup, then 'goto' it in case of a failure.

    Nevertheless, 'goto's have become less useful in C# than in C. For example, proper usage of exception handling can obviate the need of 'goto' in some scenarios.

    0 讨论(0)
  • 2020-12-17 21:07

    Code generators sometimes use labels and gotos. It can simplify the code generation logic in some cases. Goto statements are generally shunned for readability reasons, but if the code is not intended to be read then that is a moot point.

    I have also seen cases where a decompiler gets confused enough by the IL and outputs goto statements instead of the well crafted sequence of instructions that a human would have conjured. If goto statements were not legal then the decompiler might have to completely punt on that section of code. This way, at least, it can generate something that can be round-tripped.

    0 讨论(0)
  • 2020-12-17 21:09

    If (audience.LikesGoTo == true) { goto LabelThatSupportGoTo; } else { goto LabelForRejectGoTo; }

    0 讨论(0)
  • 2020-12-17 21:11

    There is nothing wrong with labels and goto's in themselves. The problem is that people tend to abuse them which does create a problem.

    Typical use of a label

    OperationStart:
      if ( !TrySomeOperation() ) {
        if ( MaybeFixOperation() ) { 
          goto OperationStart;
        }
      }
    

    You'd need to make some assertions that you couldn't hit an infitite loop, but given a reasonable set of guarantees there's nothing inherently wrong with this code.

    0 讨论(0)
提交回复
热议问题