C#笔记③
一、<<左位移与>>右位移
二进制左移与右移
左移补0
右移正补0,负补1
一般无溢出,乘2
二、is与as操作符
is操作符返回bool类型的值
is操作符
class Program
{
static void Main(string[] args)
{
Object x=new Student();
if(x is Student)
{
Student y=(Student)x;
System.Console.WriteLine("y is Student");
}
}
}
class Student
{
}
as操作符,如果是则返回此类型,不是则返回null
as操作符
class Program
{
static void Main(string[] args)
{
Object x=new Student();
Student y=x as Student;
System.Console.WriteLine(y.GetType().FullName);
}
}
class Student
{
}
三、语句
语句是高级语言才有的,汇编(ASM)和机器语言只有指令。
语句:陈述算法思想,控制逻辑走向,完成有意义的动作。
在方法体里一定是语句
三大语句:
- 标签语句
hellp:System.Console.WriteLine("Hello"); - 声明语句
- 嵌入语句
int x=100;与int x;再x=100不同。
第一种为声明时初始化,第二种为赋值,含义不同
数组初始化器 { }
block块语句是一条语句,但它包含多条语句
{
注意作用域
}
switch 没有浮点型
点击查看代码
switch()
{
case:break;
default:break;
}
抓取异常try catch finally
点击查看代码
class Program
{
static void Main(string[] args)
{
Student a=new Student();
int reuslt=a.Add("abc","2");
System.Console.WriteLine(reuslt);
}
}
class Student
{
public int Add(string str1,string str2)
{
int a=0;
int b=0;
bool hasError=false;
try
{
a=int.Parse(str1);
b=int.Parse(str2);
}
catch (OverflowException oe)
{
System.Console.WriteLine(oe.Message);
hasError=true;
}
catch(ArgumentNullException ane)
{
System.Console.WriteLine(ane.Message);
hasError=true;
}
catch(FormatException fe)
{
System.Console.WriteLine(fe.Message);
hasError=true;
}
finally
{
if(hasError)
{
System.Console.WriteLine("Fail!");
}
else System.Console.WriteLine("Done");
}
int result=a+b;
return result;
}
}
throw 谁调用谁处理
foreach语句与IEnumerator和IEnumerable
数组的基类为Array,继承了IEnumerable的类就是可以被foreach的
IEnumerator 迭代器
点击查看代码
int [] x=new int[]{1,2,3,4,5};
IEnumerator ienumer=x.GetEnumerator();
while(ienumer.MoveNext())
{
System.Console.WriteLine(ienumer.Current);
}
ienumer.Reset();
while(ienumer.MoveNext())
{
System.Console.WriteLine(ienumer.Current);
}
使用foreach
i为Current当前所指的值
int [] x=new int[]{1,2,3,4,5};
foreach (var i in x)
{
System.Console.WriteLine(i);
}
四、属性(property)
属性是用来保护,筛选字段的;propfull可以自动补全
get与set
五、索引器(indexer)
没有静态的索引器,indexer可以自动补全;
点击查看代码
class Program
{
static void Main(string[] args)
{
Student stu=new Student();
try
{
stu["Math"]=90;
System.Console.WriteLine(stu["Math"]);
}
catch (System.Exception)
{
System.Console.WriteLine("Score 为 0");
}
}
}
class Student
{
private Dictionary<string,int> Score=new Dictionary<string, int>();
public int? this[string subjuet]
{
get
{
if(Score.ContainsKey(subjuet))
{
return Score[subjuet];
}
else
{
return null;
}
}
set
{
if(value.HasValue==false)
{
throw new Exception("Score is null");
}
if(Score.ContainsKey(subjuet))
{
Score[subjuet]=value.Value;
}
else
{
Score.Add(subjuet,value.Value);
}
}
}
}

浙公网安备 33010602011771号