C# 基础 (数据结构)
C#的层级:
Variables:
C#中使用Variable必须先declare变量的类型
type name
int myNumber;
string message;
Scope:
1:注意scope的使用范围:
int myFunction()
{ int x = 10; x++; //ok for( int i=0; i<10; i++)
{ int y = x+20; //ok // other code ... } x++; //ok
y+=20; // error y is not available here }
2:父子scope或者同一scope里不可以重新声明同一个变量:
Casting:
int i = 800000; short x = 5; float f = 20.0f; f = i; //Ok. float bigger than int i = (int)f; //need casting for smaller unit
NameSpace:
C#中的NS就是一个集合,用来organize各种预制的类。命名空间NS是类的集合,可以是MicroSoft为我们准备的(.Net),也可以是我们自己包装的类。
一旦引用了名称空间,在使用这些名称空间中的类时就不必在其前加上长长的前缀了。
一般在C#里创建一个class,程序会自动为我们创建一个以project名为NS:
注意:VS里应用一个类除了要在最前面加上using字,还有在Reference文件夹下加载类。
引入名称空间:
using System;
using myClassAssembly;
名称空间的别名:
考虑有两个很长的名称空间,我需要使用它们中的类,不巧的是这两个名称空间里的类又有很多是重名的……怎么办呢?我们可以使用名称空间的别名来解决这个问题:
using Hardware = IBM.Sun.RedHat.Dell.Lenovo.HP.Oracle;
String:
"There are " +i + " seconds in a year"; //work both in Javascript and C#, but not good statement for c#
String.Fromat("There are {0} seconds in a year", i); //Good way for C#
Console.WriteLine("There are {0} seconds in a year", i); //这里Console.WriteLine不需要写String.Fromat,直接用
Switch:
1 namespace ConsoleApplication1 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 int theVal = 52; 8 switch (theVal) { 9 10 case 51: 11 Console.WriteLine("The value is 51."); 12 break; //C#每个case一定要有break 13 case 52: 14 Console.WriteLine("The out put is: {0}", ++theVal); 15 break; 16 case 53: 17 Console.WriteLine("ssss"); 18 break; 19 } 20 Console.ReadLine(); 21 } 22 } 23 }
Operations:
1: Arithmetic operators:
+ - / * % (addition, subtraction, multiplication, division, remainder)
2: Assignment operators:
= -= *= /= %=
3: Comparision Operators:
Equality check operators:
a == b, a!=b
Comparison testing operators:
a>b, a<b, a>=b, a<=b
Logical operators:
AND:&& OR:|| NOT:!
Increment/Decrement operator:
a++(先执行语句再执行a+1) int a = 20; Console.WriteLine("The result is {0}:", a++ ); //output is 20
++a(先做a+1,然后再执行语句) int a = 20; Console.WriteLine("The result is {0}:", ++ a); //output is 20
4:Type testing operator:
is operator:(return true if a given object is a certain type)
as operator:(convert a given object to another type if possible)
1 void myFunction(object obj){ 2 if(obj is Emplyee) //if obj type is Emplyee return true 3 { 4 Employee emp = obj as Employee; //null if can't be done 5 string name = emp.FirstName; 6 ..... 7 } 8 }
5:The Ternary Operator: (condition) ? true : false
eg: lowPrice = (price1 < priice2) ? price1 : price2
6: Operator procedence:
1:Multiplicative: * / %
2:Additive: + -
3:Comparison and Type Testing: < > <= >= is as
4:Equality: == !=
5:Condition AND: &&
6:Condition OR: ||
7:Ternary: ?:
8:Assignment: = *+ /= %= += -=
Constant, readonly and Enumeration: 使用目的使程序easy to read and maintain
1: Const: 静态常量,必须声明的时候就初始化,而且只能用常数值初始化
- 一般在class level声明
- 声明后必须赋值
- 声明赋值后不可以在其他位置改变原值
1 if(someVar == 32){ 2 //code here //Bad practice!What does 32 mean? 3 //What if it changes in the future? 4 } 5 6 const int FREEZING = 32; 7 if(someVar == FREEZING){ 8 //code here //Much better!Now it's clear what the code is tring to do and why. Also, if we ever decide to switch temperature scale, we just change the constant definition in one place. 9 }
Program that uses const [C#] using System; class Program { const string _html = ".html"; static void Main() { // This causes a compile-time error: Const不可以改变之前的值 _html = ""; Console.WriteLine(_html); // Access constant Console.WriteLine(Program._html); // Access constant const string txt = ".txt"; // This causes a compile-time error also: Const不可以改变之前的值 txt = ""; Console.WriteLine(txt); } }
Output .html .html .txt
2: readonly:
和Const比较,readonly是动态常量
- 初始化可以用变量初始化
- 可以在声明的时候不初始化
- 但是一定要在构造函数里初始化
- 每一个不同的构造(参数不一样)都要初始化
class Test { const float PI=3.1416f;//常量命名:全部大写 readonly float G; //可以不初始化 public Test() { G=9.80F; } public Test(float g)//每个构造函数中都要初始化;而且可以使用变量值初始化 { G=g; } }
3: Enumeration: 一组const的集合
如果我有很多Constant需要创建,我们需要用到Enumeration。Enum集合默认是int,也可以换成其他type
enmu Temperatures{ enmu Temperatures : byte {...}
REALLYCOLD, //defaults to 0
FREEZING = 32,
LUKEWAR = 65,
ROOMTEMP = 72,
HOT = 105,
BOILING = 212
}
Function: 为了可以把一大段的代码分开管理,reuse by其他程序段。
int myFunction(int x, date d){
...
Console.writeLine("We are in a function!");
return someValue;
}
1 namespace ConsoleApplication1 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 int result1; 8 int arg1 = 25; 9 result1 = formula(arg1); //or result1 = formula(25); 10 Console.WriteLine("The result is :{0}", result1); 11 Console.ReadLine(); 12 } 13 14 static int formula(int theVal) { 15 return (theVal * 2) / 3 + 15; 16 } 17 } 18 }
Data Type: Pieces of data are stored in memory locations called variables. Each piece of data can have a type, which is used to declare a variable.
45, 133.99, "Shawn zxx", shawn@gmail.com, 7/28/1980
几点注意: declare type先, 使用过程中不能更换variable的type
NullableTypes:?类型
Can represent the full range of values of their normal underlying type, along with additional value of null.
普通类型: bool b; //can be true or false; b = null; //error - can not set “b” to null;
?类型: bool? b; //can be true or false, or null int? i; //can be an integar value, or null
Declare Varable:
int myVariable = 100; string myLabel = "some string"; object someObj;
妙用Object:
1:任何type都是object的概念,object就有预制的方法。比如string 或者char
char c = 'a'; string s = "My message."
char.IsUpper(c); s.ToUpper(); //covert string to Uppercase
char.IsDigit(c); s.ToLower();
char.IsLetter(c); s.IndexOf(s2);
char.IsPunctuation(c); s.LastIndexOf(s2);
char.IsWhiteSpace(c); s.Trim();
char.ToUpper(c); string.Format(s, arg1, argN);
char.ToLower(c); string.IsNullOrEmpty(s);
2:C# everything is derived from Object, 所以object类型可以代表任何type
- 提供了一种对各种类型统一操作的方法
- 每种类型都有一些预制的function: int i = 0; i.GetType(); i.ToString(); i.Equals(j);
- Type可以和Object互相转化,所以他们可以一起以object类型作为函数的参数代入计算。
int myFunction(object obj){ if(obj is int){ int i = (int)obj; //operate on the integer mode } else if (obj is string){ string s = (string) obj; //operator on the string mode } }
Special Floating Point Value:
Char and String:
char type -> Unicode character
char myChar = 'a'; //one char is 16 bits, or 2 bytes
= '7';
='?';
string type -> a series of Unicode characters
string myMessage = "Thisi is a sample message";
string myMessage = "This string has \n a new line in it"; // "\"mean is escape character
string myDirectory = "C:\\mydir\\somefile.txt"; // "\\" mean escape backslash
string myDirectory = @"C:\mydir\somefile.txt";
string类型是不可变的,每重新赋值一次string都会创建一个新的string,所以string在loop里要小心
string result = ""; for(int c=0; c<1000; c++){ result += "some other string"; }
比较好的方法是用内部的string方法
StringBuilder sb = new StringBuilder(); for(int c=0; c<1000; c++){ sb.Append("some other string"); } result = sb.ToString();
实例:
namespace ConsoleApplication1 { class Program { static void Main(string[] args) { char myChar = 'a'; string myString = "This is a message with a \n new line and space."; Console.WriteLine("Calling char.IsUpper: {0}", char.IsUpper(myChar)); //是否是大写? Console.WriteLine("Calling char.IsDigit: {0}", char.IsDigit(myChar)); Console.WriteLine("Calling char.IsLetter: {0}", char.IsLetter(myChar));
Console.WriteLine("Calling char.IsPunctuation: {0}", char.IsPunctuation(myChar)); //是否是标点? Console.WriteLine("Calling char.IsWhiteSpace: {0}", char.IsWhiteSpace(myChar)); Console.WriteLine("Calling char.ToUpper: {0}", char.ToUpper(myChar)); //转换成大写。 Console.WriteLine("Calling char.ToLower: {0}", char.ToLower(myChar)); Console.ReadLine(); } } }
Console.WriteLine("Calling string.Trim: {0}", myString.Trim());
Console.WriteLine("Calling string.ToUpper: {0}", myString.ToUpper());
Console.WriteLine("Calling string.Trim: {0}", myString.ToLower());
Console.WriteLine("Calling string.IndexOf: {0}", string.IndexOf("a"));
Console.WriteLine("Calling string.LastIndexOf: {0}", string.LastIndexOf("a"));