【C# 基礎概念】表達式(expression)、語句(statement)、塊(block),指令(using)


官方鏈接:https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/statements-expressions-operators/

以下內容是網上找的,結合官方內容寫出的

C#中表達式(Expression)的定義

An expression is a sequence of one or more operands and zero or moreoperators that can be evaluated to a single value, object, method, ornamespace. Expressions can consist of a literal value, a method
invocation, an operator and its operands, or a simple name. Simple
names can be the name of a variable, type member, method parameter,namespace or type.

任何能得到值的運算就是表達式。表達式經過運算之后能夠產生一個值而這個值又具有自己的數據類型,所以說我們也把表達式所產生的值(很多情況下與操作符有關系)的數據類型稱為這個表達式的數據類型。例如:這有一個布爾類型的表達式

最簡單的 C# 表達式是文本(例如整數實數)和變量名稱。可以使用運算符將它們組合成復雜的表達式。----msdn

任何表達式都有值和類型兩個基本屬性

C#中的表達式

  C#中的表達式主要包括以下幾種:

       常量表達式:例如: 1、2、3、200 + 3等常量

       算術表達式:用算術運算符連接,結果是數值類型 例如:b-2

       關系表達式:用關系運算符連接,結果是布爾類型 例如:   i>5

       邏輯表達式:用邏輯運算符連接,結果是布爾類型  例如:i||j

       賦值表達式:用賦值運算符連接,運算結果的類型取決於賦值運算符左側的運算結果。i=5

       函數(方法)調用表達式:函數也稱方法,是可以完成特定功能的程序單位,通過函數調用表達式可以執行函數的特定功能,運算的結果類型取決於函數的返回值類型。 fun() 要有返回值

      lambda 表達式:b=>x+1;

      正則表達:Regex regex = new Regex(@"^(\w)+(\.\w)*@(\w)+((\.\w+)+)$");

      switch 表達式

      is 表達式

 

按運算符分對應一元運算符和二元運算符:

UnaryExpression; 一元運算表達式 如- - i BinaryExpression; 二元運算表達式 x>5、x+y 


C#語言對語句(Statement)的定義

. The actions that a program takes are expressed in statements. Common actions include
declaring variables, assigning valuE, calling methods, looping through collections, andbranching to one or another block of code, depending on a given condition. The order inwhich statements are executed in a program is called the flow of control or flow of execution.The flow of control may vary every time that a program is run, depending on how the
program reacts to input that it receives at run time.

C#語言的語句除了能夠讓程序員"順序地"(sequentially)表達算法思想,還能通過條件判斷、跳轉和循環等方法控制程序邏輯的走向
1、簡言之就是:陳述算法思想,控制邏輯走向,完成有意義的動作(action).

2、C#語言的語句由分號(;)結尾,但由分號結尾的不一定都是語句 比如 :using System;這是引入名稱空間的指令,不是語句。

 

程序執行的操作采用語句表達。 常見操作包括聲明變量、賦值、調用方法、循環訪問集合,以及根據給定條件分支到一個或另一個代碼塊。 語句在程序中的執行順序稱為“控制流”或“執行流”。 根據程序對運行時所收到的輸入的響應,在程序每次運行時控制流可能有所不同。

語句可以是以分號(;)結尾的單行代碼,也可以是語句塊中的一系列單行語句。 語句塊括在括號 {} 中,並且可以包含嵌套塊。

 

聲明語句 聲明語句引入新的變量或常量。 變量聲明可以選擇為變量賦值。 在常量聲明中必須賦值。
表達式語句 用於計算值的表達式語句必須在變量中存儲該值。
選擇語句 選擇語句用於根據一個或多個指定條件分支到不同的代碼段。 有關詳細信息,請參閱下列主題:
迭代語句 迭代語句用於遍歷集合(如數組),或重復執行同一組語句直到滿足指定的條件。 有關詳細信息,請參閱下列主題:
跳轉語句 跳轉語句將控制轉移給另一代碼段。 有關詳細信息,請參閱下列主題:
異常處理語句 異常處理語句用於從運行時發生的異常情況正常恢復。 有關詳細信息,請參閱下列主題:
Checked 和 unchecked Checked 和 unchecked 語句用於指定將結果存儲在變量中、但該變量過小而不能容納結果值時,是否允許數值運算導致溢出。 有關詳細信息,請參閱 checkedunchecked
await 語句 如果用 async 修飾符標記方法,則可以使用該方法中的 await 運算符。 在控制到達異步方法的 await 表達式時,控制將返回到調用方,該方法中的進程將掛起,直到等待的任務完成為止。 任務完成后,可以在方法中恢復執行。

有關簡單示例,請參閱方法的“異步方法”一節。 有關詳細信息,請參閱 async 和 await 的異步編程
yield return 語句 迭代器對集合執行自定義迭代,如列表或數組。 迭代器使用 yield return 語句返回元素,每次返回一個。 到達 yield return 語句時,會記住當前在代碼中的位置。 下次調用迭代器時,將從該位置重新開始執行。

有關更多信息,請參見 迭代器
fixed 語句 fixed 語句禁止垃圾回收器重定位可移動的變量。 有關詳細信息,請參閱 fixed
lock 語句 lock 語句用於限制一次僅允許一個線程訪問代碼塊。 有關詳細信息,請參閱 lock
帶標簽的語句 可以為語句指定一個標簽,然后使用 goto 關鍵字跳轉到該帶標簽的語句。 (參見下一行中的示例。)
空語句 空語句只含一個分號。 不執行任何操作,可以在需要語句但不需要執行任何操作的地方使用。

 

C#  語句塊(block)

4.3.2使用塊來分組語句
有時,需要在一個布爾表達式為true的前提下運行兩個或者更多的語句。可以將要運行的語句分組到一個新方法中,然后調用那個方法。但是,一個更簡單的做法是將語句分組到一個塊(block)中。塊是指用一對大括號來封閉的一系列語句。在下例中,兩個語句將seconds變量重置為零,並使minutes變量遞增。我們用一個塊來分組這兩個語句。假如seconds 的值等於59,就執行該塊:
int seconds =0;
int minutes =0;if 《seconds ==59)(
seconds =0:minuteB早+:
}else
seconds++;


 C# 指令

1、using指令

using指令

用於導入命名空間。這是避免使用完全限定名稱來指代某種類型的快捷方法。

using static指令

從C#6開始,我們不僅可以導入命名空間還可以使用using static指令導入特定的類型。這樣就可以直接使用類型靜態成員而不需要指定類型的名稱了。在接下來的例子中,我們這樣調用Console類的靜態方法WriteLine:

using static指令將類型的可訪問的靜態成員,包括字段、屬性以及嵌套類型(后續章節會講解),全部導入進來。同時,該指令也支持導入枚舉類型的成員

 因此如果導入了以下的枚舉類型:

using static System.Windows.Visibility;

我們就可以直接使用Hidden而不是Visibility.Hidden了:

var textBox = new TextBox { Visibility = Hidden }; 

C#編譯器還沒有聰明到可以基於上下文來推斷出正確的類型,因此在導入多個靜態類型導致二義性時會發生編譯錯誤。

using語句

 

第一種using語句寫法:這種寫法默認sw的作用在第一層花括號之間。從 C# 8.0 開始,可以對不需要使用大括號的 using 語句使用以下替代語法:

Dispose()方法將依次調用該Close()方法,所以使用using不用特有關connection閉數據鏈接。

SqlConnection如果超出范圍,則不會關閉。 因此,必須通過調用 CloseDispose顯式關閉連接。 Close 並且 Dispose 具有功能等效性

if (!readme.Exists)
{
    using StreamWriter sw = readme.CreateText();

    sw.WriteLine("this is i write first line");
    sw.WriteLine("this is i write scond line");
    sw.WriteLine("this is i write third line");
}

ILspy反編譯后

if (!readme.Exists)
        {
            StreamWriter sw = readme.CreateText();
            try
            {
                sw.WriteLine("this is i write first line");
                sw.WriteLine("this is i write scond line");
                sw.WriteLine("this is i write third line");
            }
            finally
            {
                if (sw != null)
                {
                    ((IDisposable)sw).Dispose();//該Dispose()方法將依次調用該Close()方法
                }
            }
        }

 擴展

 public bool AuthenticateUser(NetworkCredential credential)
        {
            bool validauer;
            using (var connection = Getconntion()) 
            using(var command=new SqlCommand())
            {
                connection.Open();
                command.Connection = connection;
                command.CommandText = "select * from [userinfo] where username=@username and password=@password";
                command.Parameters.Add("@username", SqlDbType.VarChar);
                command.Parameters["@username"].Value = credential.UserName;
                //  command.Parameters.Add("@username", SqlDbType.VarChar).Value = credential.UserName;
                 command.Parameters.Add("@password", SqlDbType.VarChar).Value = credential.Password;
                validauer = command.ExecuteScalar() == null ? false:true;
            }
            return validauer;


        }

反編譯后

public class UserRepository : Login.Repositories.RepositoryBase, Login.Models.IUserRepository
{
    public void Add(Login.Models.UserMode mode)
    {
        throw new System.NotImplementedException();
    }

    public bool AuthenticateUser(System.Net.NetworkCredential credential)
    {
        Microsoft.Data.SqlClient.SqlConnection connection = Getconntion();
        try
        {
            Microsoft.Data.SqlClient.SqlCommand command = new Microsoft.Data.SqlClient.SqlCommand();
            try
            {
                connection.Open();
                command.Connection = connection;
                command.CommandText = "select * from [userinfo] where username=@username and password=@password";
                command.Parameters.Add("@username", System.Data.SqlDbType.VarChar);
                command.Parameters["@username"].Value = credential.UserName;
                command.Parameters.Add("@password", System.Data.SqlDbType.VarChar).Value = credential.Password;
                return command.ExecuteScalar() != null;
            }
            finally
            {
                if (command != null)
                {
                    ((System.IDisposable)command).Dispose();
                }
            }
        }
        finally
        {
            if (connection != null)
            {
                ((System.IDisposable)connection).Dispose();
            }
        }
    }

 

第二種using語句寫法,給using語句加一個額外的花括號{},花括號標識作用域

if (!readme.Exists)
{
    {    
  using StreamWriter sw = readme.CreateText();
 
    sw.WriteLine("this is i write first line");
    sw.WriteLine("this is i write scond line");
    sw.WriteLine("this is i write third line");
        }
    int i = 0;  
}

Il編譯后的代碼

    if (!readme.Exists)
        {
            StreamWriter sw = readme.CreateText();
            try
            {
                sw.WriteLine("this is i write first line");
                sw.WriteLine("this is i write scond line");
                sw.WriteLine("this is i write third line");
            }
            finally
            {
                if (sw != null)
                {
                    ((IDisposable)sw).Dispose();//該Dispose()方法將依次調用該Close()方法
                }
            }
            int i = 0;
        }

第三種寫法、這種事比較好方式,用完sw就釋放 。using 語句中使用的對象必須實現 IDisposable 接口。

var reader = new StringReader(manyLines); using (reader) { string? item; do { item = reader.ReadLine(); Console.WriteLine(item); } while (item != null); }

第四種寫法:C#8.0 之前的寫法

using (var reader = new StringReader(manyLines)) { string? item; do { item = reader.ReadLine(); Console.WriteLine(item); } while (item != null); }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM