?符號 和 ?? 符號的作用。String的一些建立方式。結構體與類的區別。函式過載注意點及運算子的過載
阿新 • • 發佈:2018-12-10
? 符號:用於為 int,double,bool等無法賦值為null的資料型別進行null賦值
如:
int i; //預設為0
int? i; //預設為Null
?? 符號:用於判斷一個變數為Null時,給其賦一個值
如:
int? a = null;
int n = a ?? 4; //如果a為null,則 n=4 ,否則 n=a;
//Stingde 建立 1. char[] a = {'a','b','c' }; String s = new String(a); 2. String[] a = {"aaa,"bbb",""bbb"}; String s = String.Join("",a); 3. 其他建立方法
//結構體與類的區別
結構體:①不能定義解構函式,不能繼承,是值型別,類是引用型別
②建構函式預設,不能自定義建構函式
③不能在申明時賦初值
類在堆中,結構體在棧中。堆空間大,訪問速度慢。棧空間小,訪問速度快。
輕量級用結構體。
//函式過載注意點:
① 形參的型別或個數不同可以過載
② 如果只有返回引數的型別不同則不能進行過載
//運算子可過載,用關鍵字 operator 1.有一些要成對過載 如:== != 2.不是所有運算子都可以過載 3.比較運算子的過載需要返回bool,與其它的不一樣 4.無法過載 = 例子如下: public class Student { public String name; public Student(string v) { name = v; } //過載 + 符號 //注意點:運算子過載函式必須寫在對應的類的裡面,不可寫在對應的類之外 public static Student operator +(Student s1, Student s2) { return new Student(s1.name + s2.name); } } class Program { static void Main(string[] args) { Student s1 = new Student("名1"); Student s2 = new Student("名2"); //使用過載的 + 符號 Student s3 = s1 + s2; Console.WriteLine(s3.name); Console.Read(); } }