C#泛型

泛型,字面意思就是泛泛而谈的广泛形状,就是偷懒的典型。不过,程序员和工程师们,甚至科学家们发明东西并不是完备考虑的,都是线性思维,先发明出来工具,然后有漏洞再弥补。泛型就是为了省力气发明的。副作用我不知道,但是以后肯定有的。

 

K用string填充 ,就是string类型。

 

接口泛型

namespace fanxinjiekou

{

class Program

{

static void Main(string[] args)

{

Something1 v1 = new Something1();

v1.OutPut(500, 99.88d);

//Console.WriteLine("Hello World!");

Something2<uint, ushort> v2 = new Something2<uint, ushort>();

v2.OutPut(9009, 17);

Something2<char, string> v3 = new Something2<char, string>();

v3.OutPut('c', "cat");

Read();

}

}

 

 

public interface ITest<P, Q>

{

void OutPut(P x, Q y);

}

public class Something1 : ITest<int,double>

{

public void OutPut(int x,double y)

{

WriteLine("{0} - {1}", x.GetType(), x);

WriteLine("{0} - {1}\n", y.GetType(), y);

}

}

public class Something2<J,K> : ITest<J,K>

{

public void OutPut(J x, K y)

{

WriteLine("{0} - {1}", x.GetType(), x);

WriteLine("{0} - {1}\n", y.GetType(), y);

}

}

 

}

 

 

前面的我预言到了,声明:我是第一次学泛型,但是我开头说的被我说中了,就是幺蛾子的事情肯定有。后来就看到书中有泛型约束来了。

就是不能太泛,还要约束一下,唉,约束尼玛啊 ,f*k~~~

 

约束成功,现在string类型是不可以的

 

泛型方法:

namespace fanxinfangfa

{

class Program

{

static void Main(string[] args)

{

Sample s = new Sample();

// char

s.DoSomething('z');

// byte

s.DoSomething((byte)5);

// double

s.DoSomething(6.3333d);

// int

s.DoSomething(777);

 

A xa = s.GetSomething<A>();

B xb = s.GetSomething<B>();

 

Console.Read();

//Console.WriteLine("Hello World!");

}

}

class Sample

{

public void DoSomething<T>(T p) where T : struct

{

WriteLine("{0}-{1}", p.GetType().Name, p);

 

}

public T GetSomething<T>() where T:class,new()

{

return new T();

}

}

 

public class A { }

public class B { }

}

 

 

 

posted @ 2020-06-19 16:42  司徒无名  阅读(193)  评论(0编辑  收藏  举报