泛型是什么?
? 泛型:是可以在編程時(shí)难衰,不確定使用某種類型時(shí)光坝,用它來代替要使用的類献宫,使之可以接受使用者指定的類观谦,相當(dāng)于類型參數(shù)化.
? (百度百科上是這樣定義的:1.在程序編碼中一些包含類型參數(shù)的類型,也就是說泛型的參數(shù)只可以代表類靴患,不能代表個(gè)別對象仍侥。(這是當(dāng)今較常見的定義)2.在程序編碼中一些包含參數(shù)的類。其參數(shù)可以代表類或?qū)ο蟮鹊仍Ь#ㄈ藗兇蠖喟堰@稱作模板)不論使用哪個(gè)定義农渊,泛型的參數(shù)在真正使用泛型時(shí)都必須作出指明。)
泛型怎么用?
? 泛型的用法:1. 泛型方法或颊;2. 泛型類砸紊;
-
泛型方法
泛型方法可以使方法根據(jù)用戶的使用讓類型參數(shù)化, 可以在接受不同的類型;
java:
public class HelloWorld { public static void main(String[] args) { Print("Hello World"); Print(123); } public static <T> void Print (T printValue){ System.out.println(printValue); } }
c#
static void Main(string[] args) { Print("Hello world"); Print(123); Console.Read(); } public static void Print<T>(T printValue) { Console.WriteLine(printValue); }
兩個(gè)例子的打印結(jié)果都是一樣的:
Hello World 123
? C#中的泛型方法中的泛型參數(shù)(T) 是寫在方法名稱后面
? Java中的泛型方法中的泛型參數(shù)(T)是寫在返回類型的前面
? 如果要使用多個(gè)泛型參數(shù)則是在<>中兩個(gè)參數(shù)間用 ","隔開 比如<T,K>
-
泛型類(泛型接口)
泛型類中的泛型的使用區(qū)間是在整個(gè)類中, 而泛型方法是在整個(gè)方法中使用. 并且子類繼承這個(gè)泛型類,子類也可以使用此泛型(泛型接口同理)
c#
public class GenericDemo<T>
{
public T PrintValue { get; set; }
public void Print()
{
Console.WriteLine(PrintValue);
}
}
public class GenericDemoChild<T> : GenericDemo<T>
{
public void PrintChild()
{
Console.WriteLine("Chlid" + PrintValue.ToString());
}
}
Java
public class Main {
public static void main(String[] args) {
var generic = new GenericDemo<String>();
generic.PrintValue = "Hello World";
generic.Print();
var genericChild = new GenericDemoChild<Integer>();
genericChild.PrintValue = 123;
genericChild.ChildPrint();
}
}
public class GenericDemo<T> {
public T PrintValue;
public void Print( ){
System.out.println(PrintValue);
}
}
public class GenericDemoChild<T> extends GenericDemo<T> {
public void ChildPrint(){
System.out.println(PrintValue);
}
}
C#與Java泛型的的不同之處
c#:
? c#中有泛型約束,限制泛型的條件;比如限制泛型的父類必須時(shí)某某類型,現(xiàn)在泛型必須有構(gòu)造函數(shù),必須實(shí)現(xiàn)的接口;
public class Generic<T> where T : class , new(){}
where T 后面加上針對 泛型T 約束的條件
class :約束T必須時(shí)引用類型;
struct : 約束T必須時(shí)值類型;
new() : 必須有無參構(gòu)造函數(shù)(若是有其他約束條件 new()必須放在最后一個(gè)約束條件);
一個(gè)具體類名: 必須繼承自此類;
一個(gè)接口名: 必須實(shí)現(xiàn)此接口.
java:
? 通配符 ? 表示泛型中可以任意的類型
public static void main(String[] args) {
List<String> stringlist = new ArrayList<>();
stringlist.add("hel");
stringlist.add("11");
Print(stringlist);
List<Integer> intList = new ArrayList<>();
intList.add(11);
intList.add(22);
Print(intList);
}
public static void Print(List<?> list){
System.out.println(list);
}
上面的例子可以正確輸出.
在通配符?后面加上 super(下) class類名 或者 extends(上) class類名 表示通配符的上下限