c#中的多義關(guān)鍵字

new
new用三種場(chǎng)景,最常用的實(shí)例化,泛型參數(shù)時(shí)的實(shí)例化約束,第三種是顯式隱藏繼承成員。
using System;using System.Collections.Generic;using System.Data;using System.Linq;using System.Text;using System.Threading.Tasks;using static System.Console;namespace KeyWordsDemo{class NewDemo : IDemo{public void Run(){//new 1var table = new DataTable();//new 2Show<Parent>(new Child());//new 3Parent parent = new Child();parent.Print();}//new 2static void Show<T>(T t) where T : new(){WriteLine(t.GetType());}public class Parent{public virtual void Print(){WriteLine("Parent Print");}public virtual void View(){}}public class Child : Parent{//now 3public new void Print(){WriteLine("Child Print");}public override void View(){}}}}
default
default有兩種用法,一是返回類(lèi)型的默認(rèn)值,二是在switch中作為非選項(xiàng)值。
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using static System.Console;namespace KeyWordsDemo{class DefaultDemo : IDemo{public void Run(){//default 1WriteLine(default(int));WriteLine(default(bool));WriteLine(default(DateTime));WriteLine(default(string));switch (default(string)){case "":WriteLine("空字符串");break;case null:WriteLine("null");break;//default 2default:WriteLine("其他");break;}}}}
out
out有兩種用法,一是作為方法輸出參數(shù),從方法內(nèi)部返回?cái)?shù)據(jù),二是用在接口和委托的協(xié)變中,如案例中的interface IParent<out R>
using System;using System.Collections.Generic;using System.Diagnostics;using System.Linq;using System.Text;using System.Threading.Tasks;using static System.Console;namespace KeyWordsDemo{class OutDemo : IDemo{public void Run(){//out 1Computer(out int result);WriteLine(result);WriteLine("------------");IParent<object> p1 = new Child<object>();IParent<object> p2 = new Child<string>();WriteLine(p1.GetType());WriteLine(p2.GetType());p1.Print();p2.Print();p1 = p2;p1.Print();}//out 1public void Computer(out int result){result = 10;}//out 2interface IParent<out R>{R Print();}class Child<R> : IParent<R>{public R Print(){var r = default(R);WriteLine($"{typeof(R).Name}");return r;}}}}
【推薦】.NET Core開(kāi)發(fā)實(shí)戰(zhàn)視頻課程 ★★★
.NET Core實(shí)戰(zhàn)項(xiàng)目之CMS 第一章 入門(mén)篇-開(kāi)篇及總體規(guī)劃
【.NET Core微服務(wù)實(shí)戰(zhàn)-統(tǒng)一身份認(rèn)證】開(kāi)篇及目錄索引
Redis基本使用及百億數(shù)據(jù)量中的使用技巧分享(附視頻地址及觀看指南)
.NET Core中的一個(gè)接口多種實(shí)現(xiàn)的依賴注入與動(dòng)態(tài)選擇看這篇就夠了
10個(gè)小技巧助您寫(xiě)出高性能的ASP.NET Core代碼
用abp vNext快速開(kāi)發(fā)Quartz.NET定時(shí)任務(wù)管理界面
在ASP.NET Core中創(chuàng)建基于Quartz.NET托管服務(wù)輕松實(shí)現(xiàn)作業(yè)調(diào)度
現(xiàn)身說(shuō)法:實(shí)際業(yè)務(wù)出發(fā)分析百億數(shù)據(jù)量下的多表查詢優(yōu)化
評(píng)論
圖片
表情
