В чем разница, если в операторе if {} и когда в операторе if нет {}? - PullRequest
0 голосов
/ 26 марта 2019

Я занимаюсь с формами Xamarin, выполнял простое упражнение, и когда я запускал программу, кнопка не работала. Я проверил свой код и решил удалить { } из оператора if, после чего кнопка начала работать. Я замечал такое поведение время от времени.

Почему это происходит? В чем разница? Я всегда думал, что каждый блок кода должен быть внутри {}.

Может ли кто-нибудь помочь мне объяснить, чтобы я мог понять? Ниже кода Xamarin с кодом C # позади.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage Padding="20" xmlns="http://xamarin.com/schemas/2014/forms"
        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
        xmlns:local="clr-namespace:T_3000_QuotePageXMAL"
        x:Class="T_3000_QuotePageXMAL.MainPage">

<StackLayout>
    <Button Text="Next" Clicked="Button_Clicked"></Button>
    <Label Text="{Binding Source={x:Reference Slider}, Path=Value, 
     StringFormat='Font Size:{0:N0}'}"></Label>
    <Slider x:Name="Slider" Maximum="50" Minimum="16"></Slider>
    <Label x:Name="currentQuote"
           FontSize="{Binding Source={x:Reference Slider},Path=Value}"> 
    </Label>
</StackLayout>

</ContentPage>

Теперь код C # стоит:

 public partial class MainPage : ContentPage
 {
    int index = 0;
    public string[] quotes = new string[]
 {
    "Life is like riding a bicycle. To keep your balance, you must 
     keep moving.",
    "You can't blame gravity for falling in love.",
    "Look deep into nature, and then you will understand everything 
     better."
  } ;
  public MainPage()
  {
    InitializeComponent();
    currentQuote.Text = quotes[index];

  }

  private void Button_Clicked(object sender, EventArgs e)
  {
    index++;
    if (index>= quotes.Length)
    {  // when I remove the { } from this block the button works 
        index = 0;
        currentQuote.Text = quotes[index];

    } // but when they are inserted , the button does not work
  }

}

См. Комментарии к блоку кода оператора if.

1 Ответ

2 голосов
/ 26 марта 2019

Если вы удалите фигурные скобки:

if (index>= quotes.Length)
  index = 0;
  currentQuote.Text = quotes[index];

Это эквивалентно:

// only the first statement is part of the if
if (index>= quotes.Length) index = 0;

// this statement executes even if the IF statement fails
currentQuote.Text = quotes[index];

В C # скобки {} определяют блок кода.

Рекомендуется использовать операторы {} в if и else для предотвращения двусмысленности, хотя это вопрос предпочтений или стиля.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...