1. 程式人生 > 其它 >C#入門詳解筆記(三)

C#入門詳解筆記(三)

=============================Ch11=============================
例項化時初始化器
Form myForm=new Form(){Text="MyForm",FormBorderStyle=FormBorderStyle.SizableToolWindow}.ShowDialog();

string str="STRING"; 等效於 string str=new String("STRING");只是編譯器隱藏起來了

匿名型別
var Person=new{Name="Mr.Okay",Age=33};
Person.GetType().Name=<>f_AnonymousType0^2


new操作符容易造成程式緊耦合,解決方式:依賴注入
new修飾符:將子類繼承自父類的方法進行修飾,以示區分(隱藏)

十進位制轉二進位制
uint x=uint.MaxValue;
string binStr=Convert.ToString(x,2).PadLeft(32,'0');
//PadLeft左對齊,不足32位補0

檢查過程是否有溢位,系統預設unchecked
uint y=checked(x+1);

check
{
y=x+1;
}

sizeof() 物件在記憶體中佔用的位元組數

unsafe
{
int x=sizeof(Student);
//獲取自定義結構體型別的記憶體佔用,不用unsafe無法執行
}

指標->
unsafe
{
Student stu;
stu.ID=1;
stu.Score=99;
Student* pStu=&stu;
pStu->Score=100;//指標間接訪問只能操作結構體型別,不能操作引用型別
}
struct Student
{
public int ID;
public int Score;
}

string.IsNullOrEmpty()

=============================Ch12=============================
隱式型別轉換implicit
不丟失精度的轉換
子類向父類的轉換
裝箱

顯式型別轉換explicit
可能丟失精度或發生錯誤
拆箱
使用Convert類
ToString方法與各型別的轉換

Parse解析字串
資料型別.Parse(str)
double.Parse(str) 如果目標內容無法轉換成功,則報錯
TryParse(str,out result)

自定義顯式型別轉換操作符
class Stone
{
public int Age;
public static explicit operator Monkey(Stone,stone)
{
Monkey m=new Monkey()
m.Age=stone.Age/500;
return m;
}
}
class Monkey
{
public int Age;
}
Class Program
{
static void Main(string[] args)
{
Stone stone=new Stone();
stone.Age=5000;
Monkey wukongSun=(Monkey)stone;
Console.WriteLine(wukong.Age);
}
}

As與Is
if(o is Teacher)
{
Teacher t=(Teacher)o;
t.Teach();
}

Teacher t=o as Teacher;
if(t!=null)
{
t.Teach();
}

條件操作符?:
可空型別
泛型 C#3.0以後新增
Nullable<int> x=null;可簡化為int?x=null;
x=100;
Bool HasValue=x.HasValue
str=(x>=60)?"Pass":"Fail"

null合併操作符??
int?x=null;
inty=x??1;//如果x為空,則賦值為1

賦值操作符=
從右向左計算

 

感謝劉鐵錳老師傾情奉獻 視訊在B站