如果if语句具有{}和if语句不具有{}有什么区别?

时间:2019-03-26 00:09:10

标签: c# if-statement

我正在练习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 个答案:

答案 0 :(得分:2)

如果除去花括号:

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#中,括号{}定义了block代码。

{}if语句中使用else来防止歧义是一个好主意,尽管这是喜好或风格的问题。