C#泛型案例與教程
阿新 • • 發佈:2021-01-05
泛型介面–教程案例
using System;
namespace 泛型介面
{
class Program
{
static void Main(string[] args)
{
//例項化介面
IGenericInterface<System.ComponentModel.IListSource> factory =
new Factory<System.Data.DataTable, System.ComponentModel. IListSource>();
//輸出指定泛型的型別
Console.WriteLine(factory.CreateInstance().GetType().ToString());
Console.ReadLine();
}
}
//建立一個泛型介面
public interface IGenericInterface<T>
{
T CreateInstance();
}
//實現上面泛型介面的泛型類
//派生約束where T:TI(T要繼承自TI)
//建構函式約束where T: new() (T可以例項化)
public class Factory<T, TI> : IGenericInterface<TI> where T : TI, new()
{
public TI CreateInstance()
{
return new T();
}
}
}
泛型方法–教程案例
using System;
namespace 泛型介面
{
class Program
{
static void Main(string[] args)
{
int i = Finder.Find<int>(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 6);
Console.WriteLine("6在陣列中的位置:" + i.ToString());
Console.ReadLine();
}
}
public class Finder
{
public static int Find<T>(T[] items, T item)
{
for (int i = 0; i < items.Length; i++)
{
if (items[i].Equals(item))
{
return i;
}
}
return -1;
}
}
}
泛型小案例–在程式中使用泛型儲存10以下數字,然後在迴圈出來
using System;
using System.Collections.Generic;
namespace 案例3
{
class Program
{
static void Main(string[] args)
{
List<int> myList = new List<int>();
for (int i = 0; i < 10; i++)
{
myList.Add(i);
}
foreach (int i in myList)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}
泛型案例–實現泛型的繼承,其用法與普通類的繼承基本相同
using System;
namespace 案例4
{
class Program
{
static void Main(string[] args)
{
myclass1<int> mclass1 = new myclass1<int>();
myclass2<int> mclass2 = new myclass2<int>();
Console.ReadLine();
}
class myclass1<T>
{
public myclass1()
{
Console.WriteLine("這是第一個泛型類");
}
}
class myclass2<T> : myclass1<T>
{
public myclass2()
{
Console.WriteLine("這是第二個泛型類");
}
}
}
}