C# 入門學習教程(二)

文章目錄

  • 一、操作符詳解
    • 1、操作符概覽
    • 2、操作符的本質
    • 3、操作符的優先級
    • 4、同級操作符的運算順序
    • 5、 各類操作符的示例
  • 二、表達式,語句詳解
    • 1. 表達式的定義
    • 2. 各類表達式概覽
    • 3. 語句的定義
    • 4. 語句詳解

一、操作符詳解

C# 中的操作符是用于執行程序代碼運算的符號,它們可以對一個或多個操作數進行操作并返回結果。

1、操作符概覽

類別運算符
基本x.y f(x) a[x] x++ x-- new typeof default checked unchecked delegate sizeof ->
一元+ - ! ~ ++x --x (T)x await &x *x
乘法* / %
加減+ -
移位>> <<
關系和類型檢測< > <= >= is as
相等== !=
邏輯“與”&
邏輯 XOR^
邏輯 OR|
條件 AND&&
條件 OR||
null 合并??
條件?:
lambda 表達式= *= /= %= += -= <<= >>= &= ^= |= =>
  • 操作符(Operator )也譯為“運算符”
  • 操作符是用來操作數據的,被操作符操作的數據稱為操作數( Operand )

2、操作符的本質

  • 操作符的本質是函數(即算法)的“簡記法”

    • 假如沒有發明“+”、只有Add函數,算式3+4+5將可以寫成Add(Add(3,4),5)

    • 假如沒有發明“x”、只有Mul函數,那么算式3+4x5將只能寫成Add(3,Mul(4,5)),注意優先級

  • 操作符不能脫離與它關聯的數據類型

    • 可以說操作符就是與固定數據類型相關聯的一套基本算法的簡記法
    namespace CreateOperator
    {class Program{static void Main(string[] args){int x = 5;int y = 4;int z = x / y;Console.WriteLine(z);double x1 = 5;double y1 = 4;double z1 = x1 / y1;Console.WriteLine(z1);}}
    }
    • 示例:為自定義數據類型創建操作符
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;namespace CreateOperator
    {class Program{static void Main(string[] args){//List<Person> nation = Person.GetMarry(persion1,persion2);//foreach( var p in nation){//    Console.WriteLine(p.Name);//}List<Person> nation = persion1 + persion2;foreach( var p in nation){Console.WriteLine(p.Name);}}}class Person{public string Name;public static List<Person> operator +(Person p1, Person p2){List<Person> people = new List<Person> { };people.Add(p1);people.Add(p2);for (int i = 0; i < 11; i++){Person child = new Person();child.Name = p1.Name + '&' + p2.Name;people.Add(child);}return people;}}
    }

3、操作符的優先級

  • 操作符的優先級
    • 可以使用圓括號提高被括起來表達式的優先級
    • 圓括號可以嵌套
    • 不像數學里有方括號和花括號,在C#語言里“0”與"0”有專門的用途

4、同級操作符的運算順序

  • 除了帶有賦值功能的操作符,同優先級操作符都是由左向右進行運算
    • 有賦值功能的操作符的運算順序是由右向左
    • 與數學運算不同,計算機語言的同優先級運算沒有“結合率”
      • 3+4+5只能理解為Add(Add(3,4),5)不能理解為Add(3,Add(4,5))

5、 各類操作符的示例

. 操作符

namespace OperatorExample
{class Program{static void Main(string[] args){//. 操作符Form a = new Form();a.Text = "my form";a.ShowDialog();}}
}

F(x) 函數調用操作符

namespace OperatorExample
{class Program{static void Main(string[] args){//F(x) 函數調用操作符calure cc = new calure();int dd = cc.Add(1, 2);Console.WriteLine(dd);//委托Action ee = new Action(cc.print);ee();}}class calure{public int Add(int a, int b){return a + b;}public void print(){Console.WriteLine("Hello");}}
}

a[x]

namespace OperatorExample
{class Program{static void Main(string[] args){int[] intarray = new int[10];console.writeline(intarray[1]);int[] intarray2 = new int[5]{11,22,33,44,55};console.writeline(intarray2[3]);dictionary<string,student> stdob = new dictionary<string,student>();for (int i = 0; i < 101; i++){student stu = new student();stu.name = "學生" + i.tostring();stu.score = 100 + i;stdob.add(stu.name,stu);}console.writeline(stdob["學生12"].name +"; "+ stdob["學生11"].score);}}class student{public string Name;public int Score;}}

x++ x–

namespace OperatorExample
{class Program{static void Main(string[] args){int x = 100;x++;Console.WriteLine(x);x--;Console.WriteLine(x);int y = x++;Console.WriteLine(x);Console.WriteLine(y);}}
}

typeof

namespace OperatorExample
{class Program{static void Main(string[] args){Type x = typeof(int);Console.WriteLine(x.Name);Console.WriteLine(x.FullName);Console.WriteLine(x.Namespace);int a = x.GetMethods().Length;Console.WriteLine(a);foreach (var item in x.GetMethods()){Console.WriteLine(item.Name);}}}
}

default

namespace OperatorExample
{class Program{static void Main(string[] args){int a = default(int);Console.WriteLine(a);Form a = default(Form);Console.WriteLine(a == null);leved ll = default(leved);Console.WriteLine(ll);leved22 dd = default(leved22);Console.WriteLine(dd);}enum leved{mid,low,High}enum leved22{mid = 1,low = 2,High = 3,def = 0}}
}

new

namespace OperatorExample
{class Program{static void Main(string[] args){Form myForm = new Form();myForm.Text = "hello";myForm.ShowDialog();Form myFormOne = new Form() { Text = "my text" };myFormOne.ShowDialog();// var 自動推斷類型var myTx = new { text = "1234", age = 55 };Console.WriteLine(myTx.text);Console.WriteLine(myTx.age);Console.WriteLine(myTx.GetType().Name);}}
}

checked uncheckded

namespace OperatorExample
{class Program{static void Main(string[] args){uint x = uint.MaxValue;Console.WriteLine(x);string aa = Convert.ToString(x, 2);Console.WriteLine(aa);//檢測checked{try{uint y = x + 1;Console.WriteLine(y);}catch (OverflowException ex){//捕獲異常Console.WriteLine("異常");}}}}
}

**delegate **

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;namespace ddExample
{public partial class MainWindow : Window{public MainWindow(){InitializeComponent();this.myClick.Click += myClick_Click;//delegatethis.myClick.Click += delegate (object sender, RoutedEventArgs e){this.myTextBox.Text = "1111111111";};this.myClick.Click += (object sender, RoutedEventArgs e)=>{this.myTextBox.Text = "1111111111";};}void myClick_Click(object sender, RoutedEventArgs e){this.myTextBox.Text = "1111111111";}}
}

sizeof , ->

namespace OperatorExample
{class Program{static void Main(string[] args){int x = sizeof(int);Console.WriteLine(x);int x1 = sizeof(decimal);Console.WriteLine(x1);unsafe{//打印自定義數據結構的長度int y = sizeof(StudentStr);Console.WriteLine(y);//箭頭操作符,操作內存StudentStr stu;stu.age = 16;stu.score = 100;StudentStr* pStu = &stu;pStu->score = 99;Console.WriteLine(stu.score);}}}struct StudentStr{public int age;public long score;}
}

+ - 正負

namespace OperatorExample
{class Program{static void Main(string[] args){int x = 100;Console.WriteLine(x);int y = -100;Console.WriteLine(y);int z = -(-x);Console.WriteLine(z);int x1 = int.MinValue;int y1 = -x1;Console.WriteLine(x1);Console.WriteLine(y1);//溢出int y2 = checked(-x1);}}
}

~ 求反

namespace OperatorExample
{class Program{static void Main(string[] args){int x = int.MinValue;int y = ~x;Console.WriteLine(x);Console.WriteLine(y);string xstr = Convert.ToString(x, 2).PadLeft(3, '0');string ystr = Convert.ToString(y, 2).PadLeft(3, '0');Console.WriteLine(xstr);Console.WriteLine(ystr);}}
}

bool

namespace OperatorExample
{class Program{static void Main(string[] args){bool x = false;bool y = x;Console.WriteLine(x);Console.WriteLine(y);StudentTwo tt = new StudentTwo(null);Console.WriteLine(tt.Name);}}class StudentTwo{public string Name;public StudentTwo(string Name){if (!string.IsNullOrEmpty(Name)){this.Name = Name;}else{throw new ArgumentException("name is empty");}}}
}

++x --x

namespace OperatorExample
{class Program{static void Main(string[] args){int x = 100;int y = ++x;Console.WriteLine(x);Console.WriteLine(y);int x1 = 100;int z = x1++;Console.WriteLine(z);}}
}

(T)x 類型轉換

  • 隱式(implicit)類型轉換

    • 不丟失精度的轉換
    • 子類向父類的轉換
    • 裝箱顯式(explicit)類型轉換
  • 有可能丟失精度(甚至發生錯誤)的轉換,即cast拆箱使用Convert

    • ToString方法與各數據類型的Parse/TryParse方法自定義類型轉換操作符示例隱式(implicit)類型轉換
    • 不丟失精度的轉換
    • 子類向父類的轉換
    • 裝箱顯式(explicit)類型轉換
  • 有可能丟失精度(甚至發生錯誤)的轉換,即cast拆箱使用Convert類

    • ToString方法與各數據類型的Parse/TryParse方法自定義類型轉換操作符示例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace ConversionExample
{class Program{static void Main(string[] args){//隱式類型轉換//不丟失精度的轉換int x = int.MaxValue;long y = x;Console.WriteLine(y);// 子類向父類進行的隱式轉換Teacher t = new Teacher();Human h = t;h.Eat();h.Think();Animal a = h;a.Eat();//顯式類型轉Console.WriteLine(ushort.MaxValue);uint x = 65536;ushort y = (ushort)x;Console.WriteLine(y);}class Animal{public void Eat(){Console.WriteLine("Eating....");}}class Human : Animal{public void Think(){Console.WriteLine("Think ...");}}class Teacher : Human{public void Teach(){Console.WriteLine("Teacher");}}}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;namespace ConertExample
{/// <summary>/// MainWindow.xaml 的交互邏輯/// </summary>public partial class MainWindow : Window{public MainWindow(){InitializeComponent();}private void button_1_Click(object sender, RoutedEventArgs e){double x = System.Convert.ToDouble(TextBox_1.Text);double y = System.Convert.ToDouble(TextBox_2.Text);double z = x + y;//TextBox_3.Text = System.Convert.ToString(z);TextBox_3.Text = z.ToString();double x1 = double.Parse(TextBox_1.Text);double y1 = double.Parse(TextBox_2.Text);double z1 = x1 + y1;//TextBox_3.Text = System.Convert.ToString(z);TextBox_3.Text = z1.ToString();}}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace C0onvertExplameT
{class Program{static void Main(string[] args){stone ss = new stone();ss.Age = 10;//explicitMonkey mm = (Monkey)ss;//implicitMonkey mm = ss;Console.WriteLine(mm.Age);}}class stone{public int Age;//顯式類型轉換操作符 explicit public static explicit operator Monkey(stone s){Monkey aa = new Monkey();aa.Age = s.Age * 100;return aa;}//隱式類型轉換  implicit//public static implicit operator Monkey(stone s)//{//    Monkey aa = new Monkey();//    aa.Age = s.Age * 200;//    return aa;//}}class Monkey{public int Age;}
}

is as

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace ConversionExample
{class Program{static void Main(string[] args){// is運算符Teacher t = new Teacher();var res = t is Teacher;Console.WriteLine(res);Console.WriteLine(res.GetType().FullName);var res1 = t is Human;Console.WriteLine(res1);var res2 = t is object;Console.WriteLine(res2);// as 運算符object t = new Teacher();Teacher tt = t as Teacher;if (tt != null){tt.Teach();}}class Animal{public void Eat(){Console.WriteLine("Eating....");}}class Human : Animal{public void Think(){Console.WriteLine("Think ...");}}class Teacher : Human{public void Teach(){Console.WriteLine("Teacher");}}}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace ConversionExample
{class Program{static void Main(string[] args){int x = 5;int y = 6;console.writeline(x * y);double a = 5.0;double b = 4.0;var z = a * b;console.writeline(z);console.writeline(z.gettype().name);int a = 5;double b = a;console.writeline(b.gettype().name);int x1 = 5;double y1 = 2.5;console.writeline(x1 * y1);var z = x1 * y1;console.writeline(z.gettype().name);}}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace ConversionExample
{class Program{static void Main(string[] args){int x = 5;int y = 4;Console.WriteLine(x / y);double x1 = 5.0;double y1 = 4.0;Console.WriteLine(x1 / y1);double a = double.PositiveInfinity;double b = double.NegativeInfinity;Console.WriteLine(a / b);double c = (double)5 / 4;Console.WriteLine(c);double d = (double)(5 / 4);Console.WriteLine(d);}}
}

取余 %

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace ConversionExample
{class Program{static void Main(string[] args){for (int i = 0; i < 100; i++){Console.WriteLine(i % 10);}double x = 3.5;double y = 3;Console.WriteLine(x % y);   }}
}

加法 + ,減法 -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace ConversionExample
{class Program{static void Main(string[] args){//加法 +int x = 5;double y = 1.5;console.writeline(x + y);console.writeline((x + y).gettype().name);string a = "123";string b = "abc";console.writeline(a + b);//減法 -int x = 10;double y = 5.0;var z = x - y;Console.WriteLine(z);Console.WriteLine(z.GetType().Name);   }}
}

位移 >> <<

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace ConversionExample
{class Program{static void Main(string[] args){//位移,左移一位即原值*2int x = 7;int y = x << 2;Console.WriteLine(y);string xStr = Convert.ToString(x, 2).PadLeft(32, '0');Console.WriteLine(xStr);string yStr = Convert.ToString(y, 2).PadLeft(32, '0');Console.WriteLine(yStr);//右移一位即原值/2int x = 100;int y = x >> 2;Console.WriteLine(y);string xStr = Convert.ToString(x, 2).PadLeft(32, '0');Console.WriteLine(xStr);string yStr = Convert.ToString(y, 2).PadLeft(32, '0');Console.WriteLine(yStr);//一直位移的情況下,會出現類型溢出的情況,需要checked}}
}

**比較運算符 <> == != **

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace ConversionExample
{class Program{static void Main(string[] args){int a = 10;int b = 5;var c = a < b;Console.WriteLine(c);Console.WriteLine(c.GetType().FullName);char 類型比較大小,轉換成ushort 比較大小char a = 'a';char b = 'A';var res = a > b;Console.WriteLine(res);ushort au = (ushort)a;ushort bu = (ushort)b;Console.WriteLine(au);Console.WriteLine(bu);//對齊后,挨個比較unicodestring str1 = "abc";string str2 = "Abc";Console.WriteLine(str1.ToLower() == str2.ToLower());}}
}

**邏輯“與”& ; 邏輯XOR ^ ; 邏輯 OR | **

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace ConversionExample
{class Program{static void Main(string[] args){int x = 7;int y = 10;// 按位求與,二進制1為真,0為假,真假為假,真真為真,假假為假int z = x & y;Console.WriteLine(z);string xStr = Convert.ToString(x,2).PadLeft(32,'0');string yStr = Convert.ToString(y,2).PadLeft(32,'0');string zStr = Convert.ToString(z,2).PadLeft(32,'0');Console.WriteLine(xStr);Console.WriteLine(yStr);Console.WriteLine(zStr);// 按位求或,二進制1為真,0為假,真假為真,真真為真,假假為假int z = x | y;Console.WriteLine(z);string xStr = Convert.ToString(x, 2).PadLeft(32, '0');string yStr = Convert.ToString(y, 2).PadLeft(32, '0');string zStr = Convert.ToString(z, 2).PadLeft(32, '0');Console.WriteLine(xStr);Console.WriteLine(yStr);Console.WriteLine(zStr);// 按位求異或,二進制1為真,0為假,不一樣為真,一樣為假int z = x ^ y;Console.WriteLine(z);string xStr = Convert.ToString(x, 2).PadLeft(32, '0');string yStr = Convert.ToString(y, 2).PadLeft(32, '0');string zStr = Convert.ToString(z, 2).PadLeft(32, '0');Console.WriteLine(xStr);Console.WriteLine(yStr);Console.WriteLine(zStr);}}
}

條件與 && 條件或 ||

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace ConversionExample
{class Program{static void Main(string[] args){int x = 10;int y = 5;double a = 10.5;double b = 5;if(x>y && a>b){Console.WriteLine("真");}else{Console.WriteLine("假");}if (x < y || a > b){Console.WriteLine("真");}else{Console.WriteLine("假");}}}
}

null合并 ??

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace ConversionExample
{class Program{static void Main(string[] args){int? x = null;//x = 100;Console.WriteLine(x);Console.WriteLine(x.Value);int y = x ?? 1;Console.WriteLine(y);}}
}

條件 ?:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace ConversionExample
{class Program{static void Main(string[] args){int x = 60;string str = x >= 60 ? "及格" : "不及格 ";Console.WriteLine(str);}}
}

**賦值 *= += -= /= %= <<= >>= &= ^= |= **

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace ConversionExample
{class Program{static void Main(string[] args){int a = 100;int b = a += 10;Console.WriteLine(b);int c = a>>=1;Console.WriteLine(c);}}
}

二、表達式,語句詳解

1. 表達式的定義

  • 什么是表達式
    在 C# 里,表達式是由操作數和運算符組合而成的代碼片段,它能計算出一個值。操作數可以是變量、常量、字面量、方法調用等;運算符則用于指明對操作數進行何種運算。

  • C#語言對表達式的定義

    • 算法邏輯的最基本(最小)單元,表達一定的算法意圖
    • 因為操作符有優先級,所以表達式也就有了優先級

2. 各類表達式概覽

  • C#語言中表達式的分類

    • A value. Every value has an associated type.任何能得到值的運算(回顧操作符和結果類型)
    • A variable. Every variable has an associated type.
    int x = 10;
    int y;
    y = x;
    
    • A namespace.
    //A namespace
    System.Windows.Forms.Form myForm;
    
    • A type.
    // A typevar t = typeof(Int32);
    
    • A method group.例如:Console.WriteLine,這是一組方法,重載決策決定具體調用哪一個
     //A method groupConsole.WriteLine("Hello");
    

    Console.WriteLine 有19個方法供使用

    在這里插入圖片描述

    • A null literal.
         //A null literalForm MyForm = null;
    
    • An anonymous function.
    Action a = delegate () { Console.WriteLine("hello"); };
    a();
    
    • A property access.
       // a propety accessForm my = new Form();my.Text = "my Text";my.ShowDialog();
    
    • An event access.
    static void Main(string[] args)
    {Form myFo = new Form();myFo.Load += myFo_Load;myFo.ShowDialog();
    }static void myFo_Load(object sender, EventArgs e)
    {Form form = sender as Form;if (form == null){return;}form.Text = "new Text";
    }
    
    • An indexer access.
     List<int> listone = new List<int> { 1, 22, 333 };int xOne = listone[2];
    
    • Nothing.對返回值為void的方法的調用
     //NothingConsole.WriteLine("Hello");
    

在這里插入圖片描述

  • 復合表達式的求值
    • 注意操作符的優先級和同優先級操作符的運算方向

3. 語句的定義

  • Wikipedia對語句的定義

    語句是高級語言的語法

    編譯語言和機器語言只有指令(高級語言中的表達式對應低級語言中的指令),語句等價于一個或一組有明顯邏輯關聯的指令

  • C#語言對語句的定義

    • C#語言的語句除了能夠讓程序員“順序地”(sequentially)表達算法思想,還能通過條件判斷、跳轉和循環等方法控制程序邏輯的走向
    • 簡言之就是:陳述算法思想,控制邏輯走向,完成有意義的動作(action)
    • C#語言的語句由分號(;)結尾,但由分號結尾的不一定都是語句
    • 語句一定是出現在方法體

4. 語句詳解

  • 聲明語句
int xSF = 100;
var x1 = 200;
const int xC = 100;
  • 表達式語句
Console.WriteLine("Hello World");new Form();int xT = 100;
xT = 200;xT++;
xT--;
++xT;
--xT;
  • 塊語句
{int XTo = 100;if (XTo < 100)Console.WriteLine("不及格");
}
  • 標簽語句
 {hello: Console.WriteLine("Hello World");goto hello;}
  • 塊語句的作用域
 int ykuai = 100;{int xkuai = 200;Console.WriteLine(ykuai);}// 無法在塊語句外打印xkuaiConsole.WriteLine(xkuai);
  • if 語句
 int score = 59;if (score >= 80){Console.WriteLine("A");}else if (score >= 60){Console.WriteLine("B");}else if (score >= 40){Console.WriteLine("C");}else{Console.WriteLine("D");}
  • switch 語句
static void Main(string[] args)
{Level myLevel = new Level();switch (myLevel){case Level.High:Console.WriteLine(Level.High);break;case Level.Mid:Console.WriteLine(Level.Mid);break;case Level.Low:Console.WriteLine(Level.Low);break;default:Console.WriteLine("涼涼");break;}
}enum Level
{High,Mid,Low
}
  • try 語句,盡可能多的去處理異常
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;namespace ExpressionExample
{class Program{static void Main(string[] args){Count cc = new Count();int res = cc.Add("122222222", "122222222");Console.WriteLine(res);}}class Count{public int Add(string a, string b){int x = 0;int y = 0;bool error = false;try{x = int.Parse(a);y = int.Parse(b);}catch (ArgumentNullException ex){Console.WriteLine(ex.Message);error = true;}catch (FormatException ex){Console.WriteLine(ex.Message);error = true;}catch (OverflowException ex){Console.WriteLine(ex.Message);error = true;}finally{if (error){Console.WriteLine("有錯誤不能計算");}else{Console.WriteLine("一切正常");}}int z = x + y;return z;}}
}
  • while 循環語句
namespace ExpressionExample
{class Program{static void Main(string[] args){bool next = true;while (next){Console.WriteLine("請輸入數字1:");string str1 = Console.ReadLine();int a1 = int.Parse(str1);Console.WriteLine("請輸入數字2:");string str2 = Console.ReadLine();int a2 = int.Parse(str2);if (a1 + a2 == 100){next = false;Console.WriteLine("已經 100");}else{Console.WriteLine("請繼續");}}}}
}
  • do while 循環語句
namespace ExpressionExample
{class Program{static void Main(string[] args){bool nextDo = false;do{Console.WriteLine("請輸入數字1:");string str1 = Console.ReadLine();int a1 = 0;try{a1 = int.Parse(str1);}catch (Exception ex){Console.WriteLine(ex.Message);continue;}Console.WriteLine("請輸入數字2:");string str2 = Console.ReadLine();int a2 = 0;try{a2 = int.Parse(str2);}catch (Exception ex){Console.WriteLine(ex.Message);continue;}if (a1 == 100 || a2 == 100){Console.WriteLine("100 直接退出");break;}if (a1 + a2 == 100){nextDo = false;Console.WriteLine("已經 100");}else{nextDo = true;Console.WriteLine("請繼續");}} while (nextDo);}}
}
  • for 循環語句,99乘法表
namespace ExpressionExample
{class Program{static void Main(string[] args){for (int i = 1; i < 10; i++){for (int j = 1; j < 10; j++){if (i >= j){int z = i * j;Console.Write("{0} * {1} = {2} ", i, j, z);}else{Console.WriteLine("");break;}}}}}
}
  • 迭代器 與 foreach
namespace ExpressionExample
{class Program{static void Main(string[] args){int[] ints = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };IEnumerator values = ints.GetEnumerator(); //指月while (values.MoveNext()){Console.WriteLine(values.Current);}//重置values.Reset();while (values.MoveNext()){Console.WriteLine(values.Current);}// foreach 語句foreach (int i in ints){Console.WriteLine(i);}}}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/88223.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/88223.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/88223.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Linux內核深度解析:IPv4策略路由的核心實現與fib_rules.c源碼剖析

深入探索Linux網絡棧的規則引擎,揭秘策略路由如何通過多級路由表實現復雜流量控制 在Linux網絡棧中,路由決策遠不止簡單的目的地址匹配。策略路由(Policy Routing)允許根據源地址、TOS值、端口等復雜條件選擇不同的路由路徑。本文將深入剖析實現這一功能的核心源碼——net/…

【UE5】虛幻引擎的運行邏輯

UE5的運行邏輯可以分為引擎啟動流程和游戲運行流程兩個部分。引擎啟動流程一、平臺入口&引擎主流程初始化1、系統入口不同的平臺會有不同的入口。在Windows平臺&#xff0c;入口是Launch模塊下的\Engine\Source\Runtime\Launch\Private\Windows\LaunchWindows.cpp文件中的W…

大數據學習1:Hadoop單機版環境搭建

1.基礎知識介紹 Flume采集日志。Sqoop采集結構化數據&#xff0c;比如采集數據庫。 存儲到HDFS上。 YARN資源調度&#xff0c;每臺服務器上分配多少資源。 Hive是基于Hadoop的一個數據倉庫工具&#xff0c;提供SQL查詢功能&#xff0c;能將SQL語句轉變成MapReduce任務來執行…

深入理解PHP中的命名空間和自動加載機制

首先&#xff0c;讓我們來討論命名空間。PHP的命名空間是一種對代碼進行邏輯分組的機制&#xff0c;它允許開發者將函數、類和常量封裝在不同的命名空間中。這樣做的好處在于可以避免全局范圍內的名稱沖突。例如&#xff0c;你可能在你的項目中使用了一個名為"Database&qu…

學習:JS[3]數組的增刪改查+函數+作用域

一.操作數組1.改2.增arr.push(新增的內容):將一個或多個元素添加到數組的結尾arr.unshift(新增的內容):方法將一個或多個元素添加到數組的開頭,并返回該數組的長度3.刪除arr.pop():方法從數組中刪除最后一個元素,不帶參數,并返回元素的值arr.shift():方法從數組中刪除第一個元素…

從0到1搭建ELK日志收集平臺

ELK是什么 ELK 是指 Elasticsearch、Logstash 和 Kibana 這三種工具的組合&#xff0c;通常用于日志分析、數據搜索和可視化。它們分別承擔不同的功能&#xff0c;形成了強大的數據處理和分析平臺&#xff1a; Elasticsearch&#xff1a;一個分布式搜索引擎&#xff0c;擅長實時…

Qt:圖片切割

void MainWindow::on_action_slice_triggered() {QDialog *dialog new QDialog(this);dialog->setWindowTitle("切割");dialog->setFixedSize(200, 150);QVBoxLayout *vbox new QVBoxLayout;QHBoxLayout *hbox new QHBoxLayout;QLabel *label new QLabel(&…

BabelDOC,一個專為學術PDF文檔設計的翻譯和雙語對比工具

你是否也有這樣的困境&#xff0c;面對一篇學術論文&#xff0c;即使英語水平不錯&#xff0c;仍需反復查詞典&#xff0c;尤其是遇到專業術語和復雜長句&#xff0c;翻譯軟件又常常不能很好地處理學術PDF的排版&#xff0c;導致翻譯結果混亂不堪。 現在&#xff0c;解決你煩惱…

Python之面向對象和類

一.類1.類的定義&#xff1a;class 類名&#xff1a;“”“注釋 ”“”pass2.實例的創建&#xff1a;實例 類名(parameterlist)parameterlist&#xff1a;定義類時__init__()方法的參數&#xff0c;如果該方法只有一個self參數&#xff0c;parameterlist可以省略class Goose()…

【力扣 困難 C】329. 矩陣中的最長遞增路徑

目錄 題目 解法一 題目 待添加 解法一 int max(int a, int b) {return a > b ? a : b; }int search(int** matrix, int m, int n, int i, int j, int (*dp)[n]) {if (dp[i][j]) {return dp[i][j];}int len 0;if (i > 0 && matrix[i - 1][j] > matrix[i]…

Blueprints - UE5的增強輸入系統

一些學習筆記歸檔&#xff1b;增強輸入系統由兩部分組成&#xff1a;Input Action和Input Mapping ContextInput Action是輸入操作的映射&#xff08;操作中比如有移動、跳躍等&#xff09;&#xff0c;Input Mapping Context是輸入情境的映射&#xff08;對各種操作的具體按鍵…

Python 【技術面試題和HR面試題】? 動態類型、運算符、輸入處理及算法編程問答

1.技術面試題 &#xff08;1&#xff09;TCP與UDP的區別是什么&#xff1f; 答&#xff1a; ①連接性&#xff1a;TCP 面向連接&#xff0c;3次握手及4次揮手&#xff0c;建立端到端的虛鏈路像&#xff1b;UDP 無連接&#xff0c;直接發送&#xff0c;無需預先建立連接 。 ②傳…

etcd-cpp-apiv3 二次封裝

接口介紹頭文件#include <etcd/Client.hpp> #include <etcd/KeepAlive.hpp> #include <etcd/Response.hpp> #include <etcd/SyncClient.hpp> #include <etcd/Value.hpp> #include <etcd/Watcher.hpp>下面從功能介紹幾個類的概念Value &…

【網絡與系統安全】強制訪問控制——Biba模型

一、模型定義與目標 提出背景&#xff1a;1977年由Ken Biba提出&#xff0c;是首個完整性安全模型&#xff0c;與BLP模型形成對偶&#xff08;BLP關注機密性&#xff0c;Biba關注完整性&#xff09;。核心目標&#xff1a;防止低完整性信息污染高完整性信息&#xff0c;避免未授…

從架構抽象到表達范式:如何正確理解系統架構中的 4C 模型20250704

&#x1f9e9; 從架構抽象到表達范式&#xff1a;如何正確理解系統架構中的 4C 模型&#xff1f; “4C”到底是架構的組成結構&#xff0c;還是架構圖的表現方式&#xff1f;這類看似細節的問題&#xff0c;其實直擊了我們在系統設計中認知、表達與落地之間的張力。 &#x1f5…

Debian10安裝Mysql5.7.44 筆記250707

Debian10安裝Mysql5.7.44 筆記250707 1?? 參考 1 在Debian 10 (Buster) 上安裝 MySQL 5.7.44 的步驟如下&#xff1a; 1. 添加 MySQL APT 倉庫 MySQL 官方提供了包含特定版本的倉庫&#xff1a; # 下載倉庫配置包 wget https://dev.mysql.com/get/mysql-apt-config_0.8.28…

20250706-6-Docker 快速入門(上)-鏡像是什么?_筆記

一、鏡像是什么&#xfeff;1. 一個分層存儲的文件&#xff0c;不是一個單一的文件分層結構: 與傳統ISO文件不同&#xff0c;Docker鏡像由多個文件組成&#xff0c;采用分層存儲機制存儲優勢: 每層可獨立復用&#xff0c;顯著減少磁盤空間占用&#xff0c;例如基礎層可被多個鏡…

[SystemVerilog] Clocking

SystemVerilog Clocking用法詳解 SystemVerilog 的 clocking 塊&#xff08;Clocking Block&#xff09;是一種專門用于定義信號時序行為的構造&#xff0c;主要用于驗證環境&#xff08;如 UVM&#xff09;中&#xff0c;以精確控制信號的采樣和驅動時序。clocking 塊通過將信…

kong網關基于header分流灰度發布

kong網關基于header分流灰度發布 在現代微服務架構中&#xff0c;灰度發布&#xff08;Canary Release&#xff09;已經成為一種常用且安全的上線策略。它允許我們將新版本的功能僅暴露給一小部分用戶&#xff0c;從而在保證系統穩定性的同時收集反饋、驗證效果、規避風險。而作…

Go語言gin框架原理

在gin框架中&#xff0c;最關鍵的就是前綴樹&#xff0c;是很重要的。gin框架本質上是在http包的基礎之上&#xff0c;對其的一個二次封裝。這里借鑒一下小徐先生的圖&#xff0c;可能當前版本的gin可能內容有所改變&#xff0c;但大致思想還是這樣。gin框架所做的就是提供一個…