博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
泛型 Generic
阅读量:6655 次
发布时间:2019-06-25

本文共 11390 字,大约阅读时间需要 37 分钟。

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace MyGeneric.CC{    ///     /// 只能放在接口或者委托的泛型参数前面    /// out 协变covariant    修饰返回值     /// in  逆变contravariant  修饰传入参数    ///     public class CCTest    {        public static void Show()        {            {                Bird bird1 = new Bird();                Bird bird2 = new Sparrow();                Sparrow sparrow1 = new Sparrow();                //sparrow sparrow2 = new bird();            }            {                List
birdList1 = new List
(); //List
birdList2 = new List
();//两个list泛型实例不存在继承关系 List
birdList3 = new List
().Select(c => (Bird)c).ToList(); } { IEnumerable
birdList1 = new List
(); IEnumerable
birdList2 = new List
(); //Action
//Func
} { ICustomerListOut
customerList1 = new CustomerListOut
(); ICustomerListOut
customerList2 = new CustomerListOut
(); } { ICustomerListIn
customerList2 = new CustomerListIn
(); ICustomerListIn
customerList1 = new CustomerListIn
(); ICustomerListIn
birdList1 = new CustomerListIn
(); birdList1.Show(new Sparrow()); birdList1.Show(new Bird()); } { IMyList
myList1 = new MyList
(); IMyList
myList2 = new MyList
();//协变 IMyList
myList3 = new MyList
();//逆变 IMyList
myList4 = new MyList
();//协变+逆变 } } } public class Bird { public int Id { get; set; } } public class Sparrow : Bird { public string Name { get; set; } } public interface ICustomerListIn
{ //T Get(); void Show(T t); } public class CustomerListIn
: ICustomerListIn
{ //public T Get() //{ // return default(T); //} public void Show(T t) { } } ///
/// out 协变 只能是返回结果 /// ///
public interface ICustomerListOut
{ T Get(); //void Show(T t); } public class CustomerListOut
: ICustomerListOut
{ public T Get() { return default(T); } //public void Show(T t) //{ //} } public interface IMyList
{ void Show(inT t); outT Get(); outT Do(inT t); ////out 只能是返回值 in只能是参数 //void Show1(outT t); //inT Get1(); } public class MyList
: IMyList
{ public void Show(T1 t) { Console.WriteLine(t.GetType().Name); } public T2 Get() { Console.WriteLine(typeof(T2).Name); return default(T2); } public T2 Do(T1 t) { Console.WriteLine(t.GetType().Name); Console.WriteLine(typeof(T2).Name); return default(T2); } }}
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace MyGeneric{    public class Constraint    {        ///         /// 泛型约束,基类约束:        /// 1 在泛型方法内可以直接使用基类的属性和方法        /// 2 调用的时候,只能传递基类或者基类的子类        ///         /// 
/// public static void Show
(T tParameter) where T : People, IWork { Console.WriteLine("This is {0},parameter={1},type={2}", typeof(GenericMethod), tParameter.GetType().Name, tParameter.ToString()); //((People)tParameter).Id //tParameter. Console.WriteLine("id={0} name={1}", tParameter.Id, tParameter.Name); tParameter.Hi(); tParameter.Work(); //tParameter.Id //tParameter.Name } private void Linq() { } public static void ShowPeople(People tParameter) { Console.WriteLine("This is {0},parameter={1},type={2}", typeof(GenericMethod), tParameter.GetType().Name, tParameter.ToString()); //((People)tParameter).Id //tParameter. Console.WriteLine("id={0} name={1}", tParameter.Id, tParameter.Name); tParameter.Hi(); //tParameter.Work(); //tParameter.Id //tParameter.Name } public static void ShowInterface
(T tParameter) where T : ISports { tParameter.Pingpang(); } public static T Get
(T tParameter) //where T : new()//无参数构造 //where T : class//引用类型 //where T : struct//值类型 { //T t = new T(); //return t; //return null; return default(T); //return tParameter; } ///
/// 多重约束,,是而且的关系 and /// ///
public static void Many
() where T : class, ISports, IWork, new() { } }}
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace MyGeneric{    public class GenericClass
{ public void Show(T t) { Console.WriteLine(t); } public void GenericMethod
() { } public T Get(T t) { List
iList = null; return t; } } public interface IGet
{ } public delegate void GetHandler
(); public class ChildClass : GenericClass
, IGet
{ } public class ChildClass
: GenericClass
, IGet
{ private Child child = new Child(); } public class Parent { public Parent(string name) { } } public class Child : Parent { public Child():base("123") { } }}
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace MyGeneric{    public class GenericMethod    {        ///         /// 延迟声明:把参数类型的声明推迟到调用        /// 不是语法糖,而是由框架升级提供的功能        ///         /// 
/// public static void Show
(T tParameter) { Console.WriteLine("This is {0},parameter={1},type={2}", typeof(GenericMethod), tParameter.GetType().Name, tParameter.ToString()); } ///
/// 打印个object值 /// 1 任何父类出现的地方,都可以使用子类来替换 /// 2 object是一切类型的父类 /// ///
public static void ShowObject(object oParameter) { Console.WriteLine("This is {0},parameter={1},type={2}", typeof(GenericMethod), oParameter.GetType().Name, oParameter); } }}
using System;using System.Collections.Generic;using System.Diagnostics;using System.Linq;using System.Text;using System.Threading.Tasks;namespace MyGeneric{    ///     /// 1 引入泛型:延迟声明    /// 2 如何声明和使用泛型    /// 3 泛型的好处和原理    /// 4 泛型类、泛型方法、泛型接口、泛型委托    /// 5 泛型约束    /// 6 协变 逆变(选修)    ///     class Program    {        static void Main(string[] args)        {            try            {                //var list = new List
() { 1, 2, 3, 4 } //.Select(i => new //{ // id = i, // name = "Test" + i //}); //foreach (var item in list) //{ // Console.WriteLine(item.id); // Console.WriteLine(item.name); //} //List
Console.WriteLine("============================今天是泛型Generic课程================================="); int iValue = 123; string sValue = "456"; DateTime dtValue = DateTime.Now; object oValue = new object(); Console.WriteLine(typeof(List
)); Console.WriteLine(typeof(Dictionary
)); Console.WriteLine("**************************"); CommonMethod.ShowInt(iValue); //CommonMethod.ShowInt(sValue); CommonMethod.ShowString(sValue); CommonMethod.ShowDateTime(dtValue); Console.WriteLine("**************************"); CommonMethod.ShowObject(oValue); CommonMethod.ShowObject(iValue); CommonMethod.ShowObject(sValue); CommonMethod.ShowObject(dtValue); Console.WriteLine("**************************"); GenericMethod.Show
(oValue); GenericMethod.Show
(iValue); GenericMethod.Show(iValue);//类型参数可以省略,由编译器推断出来 //GenericMethod.Show
(sValue);//类型参数和参数必须匹配 GenericMethod.Show
(sValue); GenericMethod.Show
(dtValue); Console.WriteLine("**************************"); People people = new People() { Id = 11, Name = "山冈" }; Japanese japanese = new Japanese() { Id = 112, Name = "鬼子" }; Chinese chinese = new Chinese() { Id = 123, Name = "口口" }; Hubei hubei = new Hubei() { Id = 123, Name = "pig猪" }; //Constraint.Show
(people); Constraint.Show
(chinese); Constraint.Show
(hubei); Constraint.ShowPeople(people); Constraint.ShowPeople(chinese); Constraint.ShowPeople(hubei); //Constraint.ShowInterface
(people);//没有实现ISports接口 Constraint.ShowInterface
(chinese); Constraint.ShowInterface
(hubei); Constraint.ShowInterface
(japanese); //Constraint.Show
(japanese);//虽然Japanese有ID和Name,但是因为不是People,所以不能调用 //Constraint.Show
(iValue);//约束后,只能按约束传递 #region Monitor { long commonTime = 0; long objectTime = 0; long genericTime = 0; { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i < 1000000000; i++) { ShowCommon(iValue); } stopwatch.Stop(); commonTime = stopwatch.ElapsedMilliseconds; } { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i < 1000000000; i++) { ShowObject(iValue); } stopwatch.Stop(); objectTime = stopwatch.ElapsedMilliseconds; } { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i < 1000000000; i++) { ShowGeneric
(iValue); } stopwatch.Stop(); genericTime = stopwatch.ElapsedMilliseconds; } Console.WriteLine("commonTime = {0} objectTime = {1} genericTime = {2}", commonTime, objectTime, genericTime); } #endregion } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.Read(); } private static void ShowCommon(int iParameter) { } private static void ShowObject(object oParameter) { } private static void ShowGeneric
(T tParameter) { } }}
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace MyGeneric{    public interface ISports    {        void Pingpang();    }    public interface IWork    {        void Work();    }    public class People    {        public int Id { get; set; }        public string Name { get; set; }        public void Hi()        { }    }    public class Chinese : People, ISports, IWork    {        public string Tradition { get; set; }        public void SayHi()        {            Console.WriteLine("吃了么?");        }        public void Pingpang()        {            Console.WriteLine("打乒乓球...");        }        public void Work()        {            throw new NotImplementedException();        }    }    public class Hubei : Chinese    {        public string Changjiang { get; set; }        public void Majiang()        {            Console.WriteLine("打麻将啦。。");        }    }    public class Japanese : ISports    {        public int Id { get; set; }        public string Name { get; set; }        public void Pingpang()        {            Console.WriteLine("打乒乓球...");        }    }}

 

转载于:https://www.cnblogs.com/zhengqian/p/8490548.html

你可能感兴趣的文章
Java中能否利用函数参数来返回值
查看>>
java基础
查看>>
Maven学习——安装与修改Maven的本地仓库路径
查看>>
DESCRIBE TABLE
查看>>
Java之建造者模式(Builder Pattern)(转)
查看>>
java之MySQL的使用
查看>>
c#简单自定义异常处理日志辅助类
查看>>
[Node.js]回调函数
查看>>
[数分笔记]问题1.1 T1
查看>>
HDOJ_ACM_I love sneakers!
查看>>
力扣算法题—097交错字符串
查看>>
windows的ftp命令小结
查看>>
用插值方法构造多项式证明中值问题
查看>>
不要把时间浪费在QQ上
查看>>
$\mathbf{R}$上开集的构造
查看>>
20155229 2016-2017-2《Java程序设计》课程总结
查看>>
更改电脑用户名(可更改C:\Users\用户名)
查看>>
一位学软件工程的学生对软件行业的困惑
查看>>
生命周期
查看>>
.bash_profile和.bashrc的区别(如何设置生效)
查看>>