c#中的多义关键字

new
new用三种场景,最常用的实例化,泛型参数时的实例化约束,第三种是显式隐藏继承成员。
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有两种用法,一是返回类型的默认值,二是在switch中作为非选项值。
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有两种用法,一是作为方法输出参数,从方法内部返回数据,二是用在接口和委托的协变中,如案例中的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实战项目之CMS 第一章 入门篇-开篇及总体规划
【.NET Core微服务实战-统一身份认证】开篇及目录索引
Redis基本使用及百亿数据量中的使用技巧分享(附视频地址及观看指南)
.NET Core中的一个接口多种实现的依赖注入与动态选择看这篇就够了
用abp vNext快速开发Quartz.NET定时任务管理界面
评论
