1.密閉類和靜態(tài)類
1、密閉類是修飾為sealed的類, sealed不能有子類。一般只有系統(tǒng)中的一些基本類聲明為sealed。面試題:是否可以編寫一個(gè)類繼承自String類?
答:不能,因?yàn)閟tring被聲明為了sealed了
2、靜態(tài)類:聲明為static的類,不能實(shí)例化,只能定義static成員。通常用他定義擴(kuò)展方法
3、C#3.0特性:擴(kuò)展方法。聲明靜態(tài)類,增加一個(gè)靜態(tài)方法,第一個(gè)參數(shù)是被擴(kuò)展類型的標(biāo)記為this,然后在其他類中可以直接調(diào)用,本質(zhì)上還是對靜態(tài)方法調(diào)用提供的一個(gè)“語法糖”,也可以用普通靜態(tài)方法的方式調(diào)用,所以不能訪問private和protected成員。例子:給String擴(kuò)展一個(gè)IsEmail方法。自己寫的機(jī)會(huì)比較少。
usingSystem;
usingSystem.Collections;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
namespaceTestConsole
{
??? class Program
??? {
??????? static void Main(string[] args)?{
??????????? string str = "HelloWorld!";
? str.ShowMsg(str);
??????????? Console.ReadKey();
??????? }
}
??? #region 擴(kuò)展方法
??? static class MyString
??? {
??????? public static void ShowMsg(this string a, stringmsg)
??????? {
??????????? Console.WriteLine(msg);
??????? }
??? }
??? #endregion 擴(kuò)展方法
}
2.深拷貝、淺拷貝
如果拷貝的時(shí)候共享被引用的對象就是淺拷貝,如果被引用的對象也拷貝一份出來就是深拷貝。(深拷貝就是說重新new一個(gè)對象,然后把之前的那個(gè)對象的屬性值在重新賦值給這個(gè)用戶)
usingSystem;
usingSystem.Collections;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
namespaceTestConsole
{
??? class Program
??? {
??????? static void Main(string[] args)
??????? {
??????????? MyCopy copy1 = new TestConsole.MyCopy();
??????????? copy1.Name ="蛋蛋";
??????????? copy1.Age =18;
??????????? MyCopy copy2 = copy1;//淺拷貝
??????????? MyCopy copy3 = new MyCopy();
??????????? copy3.Name =copy1.Name;
??????????? copy3.Age =copy1.Age;//深拷貝
??????????? Console.ReadKey();
??????? }
}
??? #region 深拷貝、淺拷貝
??? class MyCopy
??? {
??????? public string Name { get; set; }
??????? public int Age { get; set; }
??? }
??? #endregion 深拷貝、淺拷貝
}},? "JWoIVy?Z?T%?