一些知識(shí)的提升:密閉類和靜態(tài)類、深拷貝和淺拷貝

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%?

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容