在这里,小编对想要在.Net方面有更深造诣的人,做一希望必要的知识补充!
下面是关于泛型方法,泛型接口,泛型类的介绍:
1.泛型类
声明一个类
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AutofacDemo { //泛型接口 interface IFanXingable<T> { T SayNumber(T t); } //泛型类 public class FanXing<T>// where T:class,new() { T[] arryStrings = new T[] { }; //索引器 public T this[int index] { get { return arryStrings[index]; } set { arryStrings[index] = value; } } //泛型方法 public T Add<T>(T str) { return str; } } }
在需要用到它的地方调用
using System; using System.CodeDom; using System.Collections.Generic; using System.Data.Common; using System.Linq; using System.Reflection; using System.Security.Authentication.ExtendedProtection; using System.Text; using Autofac; using Autofac.Configuration; namespace AutofacDemo { //测试泛型 public class Person { public string Name { get; set; } public int Age { get; set; } public void Add<T>(T t) { Console.WriteLine(t); } } static void Main(string[] args) { //实例化 FanXing<string> fanXing=new FanXing<string>(); fanXing[0] = "aaa1"; fanXing[1] = "aaa2"; fanXing[2] = "aaa3"; fanXing[3] = "aaa4"; FanXing<int> fanXingInt=new FanXing<int>(); fanXingInt[0] = 1; fanXingInt[2] = 2; fanXingInt[3] = 4; fanXingInt[4] = 3; FanXing<Person> fanXingClass = new FanXing<Person>(); fanXingClass[0] = new Person() {Name = "guo",Age=21}; fanXingClass[0] = new Person() {Name = "yang",Age = 20}; //方法泛型 泛型是数据类型的抽象 数据类型是对象的抽象 Console.ReadKey(); } } }
如何实现泛型接口呢?这个也简单,声明一个类,直接继承你所定义的接口
//实现接口 public class MyClass : IFanXingable<Int32> { public int SayNumber(int t) { return t; } }
至于方法泛型呢?更加简单,基类里边弄一个泛型方法,子类继承的时候去实现,不过我想一下啊,用到的地方也就是那么几种情况,比如说写分页查询的时候,有个排序,是按年龄排?还是按ID排序,亦或是按日期排?这都是一个不确定的因数,所以这里是泛型方法的使用最恰到好处的地方!
下载说明
☉本站所有源码和资源均由站长亲自测试-绝对保证都可以架设,运营!
☉如源码和资源有损坏或所有链接均不能下载,请告知管理员,
☉本站软件和源码大部分为站长独资,资源购买和收集,放心下载!
☉唯一站长QQ:1004003180 [人格担保-本站注重诚信!]
☉购买建议E-mail:1004003180@qq.com 源码收购 E-mail:1004003180@qq.com
☉本站文件解压密码 【文章内都自带解压密码,每个密码不同!】