C# if语句有{}和if语句没有{}有什么区别?

C# if语句有{}和if语句没有{}有什么区别?,c#,if-statement,C#,If Statement,我正在练习Xamarin表单,我在做一个简单的练习,当我运行程序时,按钮不起作用。我检查了代码,决定从if语句中删除{},然后按钮开始工作。我时常注意到这种行为 为什么会发生这种情况?有什么区别?我一直认为每个代码块都必须在{}中 有谁能帮我解释一下,让我明白吗?下面是Xamarin代码,后面是C#代码 <?xml version="1.0" encoding="utf-8" ?> <ContentPage Padding="20" xmlns="http://xamarin.

我正在练习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>
}


请参阅if语句代码块上的注释。

如果删除大括号:

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
语句中使用
{}
是一个好主意,以防止歧义,尽管这是一个偏好或风格的问题。

这些信息可以在文档中很容易找到,如果您习惯于寻找这种类型的东西,这对您来说确实更好,它的效率更高,你会学得更快、更多,但这个问题足够具体,值得回答。我非常怀疑以前在这个表单中有人问过这个问题。格式化文档(Ctrl+K,Ctrl+D)是一个被低估的特性。如果没有大括号,重新格式化文档,它会让您更好地了解没有大括号会发生什么。根据经验,您应该始终使用大括号,除非依赖于if条件的代码正好是一条语句,即使在这种情况下,您仍然可以(有些人甚至会说应该)使用大括号。如果我写:--if,也是一样的(index>=quotes.Length){index=0;}else{currentQuote.Text=quotes[index];}--我是否正确?否。else块仅在IF为false时执行。在本例中,第二条语句始终执行oooh ok…我理解…感谢您消除我的疑虑
// 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];