using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 泛型
{
public class Stack<T> //类的泛型
{
private T[] _item;
public void Push(T item)
{
Console.WriteLine(item);
}
public Stack(int i)
{
this._item = new T[i];
}
public static string name = "静态";
}
public class Method
{
public int level = 5;
public void FangFa<T>(T t)where T:class //方法的泛型
{
Console.WriteLine(t);
}
}
public class Test<M> where M:Method ,new() //泛型的约束 类型M被约束为只能是Method类型
{
public void Push(M m)
{
Console.WriteLine(m.level);
}
public Test()
{
}
}
public class AA<T>where T:struct //泛型约束 struct值类型 class引用类型
{
public void Push(T t)
{
Console.WriteLine(t);
}
}
public class CC
{
public CC(int a)
{
Console.WriteLine(6);
}
public CC()
{
}
}
public class BB<T> where T :CC ,new() //有了new()CC必须具有公共五参数的构造函数的非抽象类型,才能用作泛型BB类的参数
{
public BB(string str)
{
Console.WriteLine(2);
}
}
class Program
{
static void Main(string[] args)
{
Stack<int> a = new Stack<int>(100);
a.Push(60);
Stack<string> b = new Stack<string>(10);
b.Push("likang");
Method m = new Method();
Test<Method> c = new Test<Method>();
c.Push(m);
AA<double> aa = new AA<double>();
aa.Push(2.2);
AA<char> bb = new AA<char>();
bb.Push('y');
Console.WriteLine(sizeof(char)); //char占两个字节,方法sizeof()用来测试其长度
m.FangFa<Test<Method>>(c);
BB<CC> _b = new BB<CC>("likang");
Console.Read();
}
}
}
对于func<>和action<>的学习:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Action和Func
{
public delegate void buy();
class Test01
{
public static void buyBook()
{
Console.WriteLine("买书");
}
public static void buyWater(string str)
{
Console.WriteLine("买的水是:"+str);
}
public static void buyCar(string str,int money)
{
Console.WriteLine("我今天买了一个名字是{0}的书,花了我{1}钱",str,money);
}
public static string buyHouse()
{
return "准备结婚,买了一个房子";
}
public static int buyFire(int name)
{
return name;
}
}
class Program
{
static void Main(string[] args)
{
//buy b = Test01.buyBook; //委托
//b();
Action _action = new Action(Test01.buyBook);//封装一个方法,该方法没有参数并且没有返回值
_action();
Action<string> _actionH = new Action<string>(Test01.buyWater); //封装一个方法,该方法只有一个参数并且没有返回值
_actionH("农夫山泉");
Action<string, int> _actionT = new Action<string, int>(Test01.buyCar); //两个参数,无返回值,最多可以封装16个参数
_actionT("蒙拉丽莎的眼泪",60);
Func<string> _func = new Func<string>(Test01.buyHouse); //封装一个方法,没有参数,有返回值
Console.WriteLine( _func());
Func<int, int> _func2 = new Func<int, int>(Test01.buyFire); //一个参数,有返回值
Console.WriteLine(_func2(2));
Console.Read();
}
}
}