一、泛型与类
二、泛型与接口
三、泛型与类型成员
四、泛型与委托
五、泛型约束
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /* 泛型与接口 * 泛型与类 * 泛型方法 * 泛型与委托 * .NET类库中自带的 Action Func 泛型委托 */ namespace MyApp { public delegate void MyDel<T>(T arg); //自己定义的泛型委托 public interface IDemo<T> { void SetObject(T t); T GetObject { get; } } public class TestA : IDemo<float> { private float _val; public void SetObject(float t) { this._val = t; } public float GetObject { get { return this._val; } } } public class TestB<U> : IDemo<U> { private U _value; public void SetObject(U t) { this._value = t; } public U GetObject { get { return this._value; } } } /* 泛型与方法 */ public class Test { public T[] MakeArray<T>(T defaultVal, int len) { Array arr = Array.CreateInstance(typeof(T), len); for (int i = 0; i < arr.Length; i++) { arr.SetValue(defaultVal, i); } return (T[])arr; } } class Program { static void Main(string[] args) { TestA ta = new TestA(); ta.SetObject(10.217f); Console.WriteLine("TestA类的属性值为:{0}",ta.GetObject); TestB<string> tb = new TestB<string>(); tb.SetObject("hello world"); Console.WriteLine("TestB类的属性值为:{0}", tb.GetObject); Test t = new Test(); DateTime[] data = t.MakeArray<DateTime>(DateTime.Now, 4); Console.WriteLine(string.Join("\n",data)); MyDel<int> test1 = new MyDel<int>(FuncTest); //调用委托 test1(500); Console.ReadKey(); } private static void FuncTest(int arg) { Console.WriteLine("\n参数类型为{0},值为{1}",arg.GetType().Name, arg); } } }
文章来源: C#泛型