C#泛型。

作用:

使用泛型可以实现算法重用。 

 class Program { static void Main(string[] args) { MyClass<string> myClass = new MyClass<string> ; } } //泛型类 class MyClass<H> { public void Say(H arg) { Console.WriteLine(arg); } } //泛型方法 public class Class1 { public void Say<H>(H msg) { Console.WriteLine(msg); } } //泛型接口 public interface IInterface<H> { H Say(); void Say1(H msg); } //实现泛型接口方法一,普通类实现泛型接口。 public class Class2 : IInterface<string> { public string Say() { throw new NotImplementedException(); } public void Say1(string msg) { throw new NotImplementedException(); } } //方法二,泛型类实现泛型接口。 public class Class3<U> : IInterface<U> { public U Say() { throw new NotImplementedException(); } public void Say1(U msg) { throw new NotImplementedException(); } }

 泛型约束:

 Myclass<T> where T : struct  必须值类型 / :class 必须引用类型

多个:

Myclass<T,K,W,R,P> 

 where T: struct

 where K :class

where W : 接口   必须实现某个接口

where R:K    R必须是K类型或K的之类。

where P : class,new()    必须引用  且带无参构造函数。   逗号隔开。  new必须写在最后。

 

相关文章