扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
using System; using System.Collections.Generic; using System.Text; namespace GenericTest { class Program { static void Main(string[] args) { //使用string,int来实例化Test<T,S>类 Test<string, int> t = new Test<string, int>("SHY520",22); //调用泛型类中的方法 t.SetValue(); } } /**//// <summary> /// 定义一个泛型类,该类有两个类型参数,分别是T,S /// http://pw.cnblogs.com /// </summary> /// <typeparam name="T">类型参数</typeparam> /// <typeparam name="S">类型参数</typeparam> public class Test<T,S> { //泛型类的类型参数可用于类成员 private T name; private S age; public Test(T Name,S Age) { this.name = Name; this.age = Age; } public void SetValue() { Console.WriteLine(name.ToString()); Console.WriteLine(age.ToString()); } } } |
//如果这样写的话,显然会报找不到类型T,S的错误 public class TestChild : Test<T, S> { } //正确的写法应该是 public class TestChild : Test<string, int>{ } public class TestChild<T, S> : Test<T, S> { } public class TestChild<T, S> : Test<String, int> { } |
public interface IList<T> { T[] GetElements(); } public interface IDictionary<K,V> { void Add(K key, V value); } // 泛型接口的类型参数要么已实例化 // 要么来源于实现类声明的类型参数 class List<T> : IList<T>, IDictionary<int, T> { public T[] GetElements() { return null; } public void Add(int index, T value) {} } |
using System; using System.Collections.Generic; using System.Text; namespace GenericTest { //定义一个委托,类型参数为T,返回值类型T //泛型委托支持在返回值和参数上应用类型参数 delegate string GenericDelete<T>(T value); class test { static string F(int i) { return "SHY520"; } static string G(string s) { return "SHY520"; } static void Main(string[] args) { GenericDelete<string> G1 = G; GenericDelete<int> G2 = new GenericDelete<int>(F); } } } |
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。
现场直击|2021世界人工智能大会
直击5G创新地带,就在2021MWC上海
5G已至 转型当时——服务提供商如何把握转型的绝佳时机
寻找自己的Flag
华为开发者大会2020(Cloud)- 科技行者