1. 程式人生 > 實用技巧 >ASPxGridView 範例4 :ASPxGridView 行選擇、多表頭設計、資料匯出、主表細表等功能實現

ASPxGridView 範例4 :ASPxGridView 行選擇、多表頭設計、資料匯出、主表細表等功能實現

1. 概述

  泛型是指任意引用型別,又叫引數化型別 (ParameterizedType),對具體型別的使用起到輔助作用,類似於方法引數。

泛型存在形式:

  • 泛型類
  • 泛型介面
  • 泛型方法

泛型的好處:

  • 提高程式碼重用性。
  • 防止型別轉換異常,提高程式碼安全性。

注意:

  • 泛型一般只會與集合類結合使用。
  • 泛型只能傳遞引用型別,如果要傳遞基本型別,可以使用其包裝類。
  • 泛型不能宣告為靜態量。
  • 泛型是 JDK1.5 版本引入的新特性,JDK1.7版本以後,可以不顯示聲明後面的型別。(菱形泛型,如:ArrayList<String> str = new ArrayList<>()

2. 建立泛型類

public class MyClass<T> {
    T t;
}
  • 建立泛型類使,泛型宣告在類名後,用尖括號包裹(一般用大寫字母代表泛型,如:T、E、K、V)。
  • 如果宣告多個泛型,可以用逗號隔開,如:<K,V>
  • 泛型類可以在其內部使用泛型型別,如下例項。
public class MyGeneric<T> {
    T t;

    public T getT() {
        return t;
    }

    public void show(T s) {
        System.out.println(s);
    }
}

class TestDemo() {
    public static void main(String[] args) {
        MyGeneric<String> s = new MyGeneric<>();
        s.t = "hello";
        String t = s.getT();
        System.out.println(t);
        s.show("world");
    }
}

3. 定義泛型介面及其實現類

public interface MyInterface<T> {
}

class MyInterfaceImpl1<E> implements MyInterface<E> {
}

class MyInterfaceImpl2 implements MyInterface<String> {
}
  • 泛型介面宣告與泛型類一致。
  • 泛型介面的實現類有兩種寫法:
    • 可以用泛型類實現泛型介面。
    • 可以用普通類實現泛型介面,但是需要指定泛型型別,這樣就將泛型寫死了,變成普通類。
// 泛型介面
public interface MyInterface<T> {
    T getT(T t);
}
// 泛型介面實現類1
class MyInterfaceImpl1<E> implements MyInterface<E>{

    @Override
    public E getT(E e) {
        return e;
    }
}
// 泛型介面實現類2
class MyInterfaceImpl2 implements MyInterface<String> {

    @Override
    public String getT(String s) {
        return s;
    }
}
// 測試類
class TestDemo {
    public static void main(String[] args) {
        MyInterface<String> m1 = new MyInterfaceImpl1<>();
        String s1 = m1.getT("hello");
        System.out.println(s1);

        MyInterfaceImpl2 m2 = new MyInterfaceImpl2();
        String s2 = m2.getT("world");
        System.out.println(s2);
    }
}

4. 泛型方法

public <T> T get(T t){}

public <T> void (T t){}
  • 宣告泛型方法時,泛型宣告在返回值的前面。
  • 泛型方法可以宣告在普通類中。
  • 泛型方法上的泛型宣告只屬於該方法,不能被其他方法使用。
// 普通類中宣告泛型方法
public class MethodDemo {
    public static <T> void show(T t) {
        System.out.println(t);
    }

    public static <T> T get(T t) {
        return t;
    }
}
// 測試類
class DemoTest {
    public static void main(String[] args) {
        MethodDemo.show("hello,word!");
        MethodDemo.show(2020 - 1024);
        String s = MethodDemo.get("世界聚焦於你!");
        System.out.println(s);
    }
}

5. 參考連結