使用泛型可以是算法“代码”重用。因为使用泛型,改变的仅仅是数据类型。
《1》
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _自定义泛型
{
//---------------------定义一个泛型类
public class MyClass<T>
{
public void SayHello(T msg)
{
Console.WriteLine(msg);
}
}
//---------------------定义一个泛型方法
public class Class1
{
public void SayHello<T>(T msg)
{
Console.WriteLine(msg);
}
}
//---------------------定义一个泛型接口
public interface IFace<T>
{
T SayHi();
void SayHello(T msg);
}
//实现这个泛型接口有两种
//1.普通类实现泛型接口
public class Class2 : IFace<string>
{
public string SayHi()
{
return "你好";
}
public void SayHello(string msg)
{
Console.WriteLine("我是一个普通类继承了泛型接口中的方法");
}
}
//2.泛型类实现泛型接口
public class Class3<U>:IFace<U>
{
public U SayHi()
{
return default(U);
}
public void SayHello(U msg)
{
Console.WriteLine(msg);
}
}
class Program
{
static void Main(string[] args)
{
MyClass<string> mc = new MyClass<string>();
mc.SayHello("are you ok?");
Class3<string> c3 = new Class3<string>();
c3.SayHi();
c3.SayHello("你好吗?我很好");
Console.ReadKey();
}
}
}
《2》
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 泛型
{
class Text<T,N>
{
public T Name { get; set; }
public N Age { get; set; }
public User adder { get; set; }
public void SayHello()
{
Console.WriteLine("我的名字叫{0},为{1}岁了,我有个兄弟叫{2},今天年{3}岁了", Name, Age,adder.Name,adder.Age);
}
}
class User
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main(string[] args)
{
Text<string, int> t = new Text<string, int>();
t.Name = "黎明";
t.Age = 15;
t.adder = new User() { Name = "郭富城", Age = 28 };
t.SayHello();
Text<string, int> t2 = new Text<string, int>() { Name = "刘德华", Age = 18, adder = new User() { Name="李小龙",Age=19} };
t2.SayHello();
Console.WriteLine("abcd".IndexOf("c"));
Console.ReadKey();
}
}
}
《3》
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 泛型
{
class MyList<T>
{
public List<T> _list { get; set; }
public MyList()
{
this._list = new List<T>();
}
// public delegate int FuncAllLen(List<T> list);等同于Func<List<T>, int> FuncAllLen
public int AllLen(Func<List<T>, int> FuncAllLen) //将一个委托FuncAllLen作为参数
{
if (FuncAllLen != null)
{
return FuncAllLen(_list);
}
else
{
return 0;
}
}
}
class Program
{
static void Main(string[] args)
{
//根据这个list的元素,我做不同的操作。例如这里的list元素是bool,现在要技术这里list里为true的元素有几个?
var list = new MyList<bool>();
list._list.Add(true);
list._list.Add(false);
list._list.Add(true);
//因为AllLne方法里的参数是一个返回值为int,参数类型为List<T>的匿名委托,那么在这里我就要实现这个委托
int intRef = list.AllLen(
plist =>
{
int i = 0;
foreach (var item in plist)
{
if (item) //如果item为true
{
i++;
}
}
return i;
}
);
Console.ReadKey();
}
}
}