文档01_基础
C#重学
1. 关于var 的使用
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleAppModel01 { class Program { static void Main(string[] args) { Console.WriteLine("hello world!"); var i = 10; Console.WriteLine("Is " + i.GetType().ToString());//var 会推断出使用的类型,但必须初始化; Console.ReadKey(); } } }
2.关于作用域
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleAppModel01 { class Program { static int n=30; int m = 30; static void Main(string[] args) { Console.WriteLine("hello world!"); var i = 10; int n = 20; int m = 40; Program p = new Program(); Console.WriteLine("Is " + i.GetType().ToString());//var 会推断出使用的类型,但必须初始化; //可以区分的名称和作用域的标示符 Console.WriteLine("Is " + n.GetType().ToString()+" "+n.ToString()); Console.WriteLine("Is " + Program.n.GetType().ToString() +" "+ Program.n.ToString()); Console.WriteLine("Is " + m.GetType().ToString() + " " + m.ToString()); Console.WriteLine("Is " + p.m.GetType().ToString() + " " + p.m.ToString()); p.ch(); Console.ReadKey(); } public int b=11; public void ch() { int b=12; Console.WriteLine("" + b.ToString()) ; Console.WriteLine("" + this.b.ToString()); } } }
可以不同域定义变量,但不能产生域与域之间的冲突
在static中的错误
错误 3 关键字“this”在静态属性、静态方法或静态字段初始值中无效 D:\vs2010Workspace\TestProject\ConsoleAppModel01\ConsoleAppModel01\Program.cs 28 13 ConsoleAppModel01
3.关于流畅控制
if(表达式(bool类型))
{ 表达式 }
else
{ 表达式 }
注意等号判断,必须是==
switch(索引号)//可以是数字,字母,变量,枚举
{
case 索引号 :表达式;break;//索引号 必须是常量
default:默认表达式;break;
}//注意break的使用
while(表达式(bool类型))
{
语句
}
for(初始化变量;条件表达式;计算表达式)
{
语句
}
当然也可以这样写
bool b ;
for (b=true;b ; b=false)
{
Console.WriteLine("Is 3 123");
}
经常性写法
for (int i=0;i<10 ; i++)
{
Console.WriteLine("Is 3 123 "+i);
}
ps:个人最喜欢用的是for,不解释。
continue与break
continue跳过当前循环,break跳出循环
关于二元运算||与&&
||运算会出现短路,&&没有短路
class Program{ static void Main(string[] args) { Program p = new Program(); if(p.ch("1")||true) { Console.WriteLine("不短路"); } if ( true||p.ch("2")) { Console.WriteLine("短路"); } Console.ReadKey(); } public bool ch(string str) { Console.WriteLine("短路"+str ); return false; } }