首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 2.0 泛型程式設計基礎(二):泛型類別繼承規則、泛型介面/委派定義與實作完整語法

     編輯:關於C語言

泛型類別繼承兩種合法形式

  1. 父類別型別參數已具體化 → 子類別可非泛型
  2. 父類別型別參數未具體化 → 父子皆為泛型且參數相同

// 錯誤:找不到 T, S
public class TestChild : Test { }

// 正確:父類別具體化
public class TestChild : Test { }

// 正確:父子同參數
public class TestChild : Test { }

// 正確:子類別泛型,父類別具體化
public class TestChild : Test { }

泛型介面:規則同泛型類別


public interface IList { T[] GetElements(); }
public interface IDictionary { void Add(K key, V value); }

// 實作:型別參數具體化或來源於實作類別
class List : IList, IDictionary
{
    public T[] GetElements() => null;
    public void Add(int index, T value) { }
}

泛型委派


using System;
using System.Collections.Generic;
using System.Text;

namespace GenericTest
{
    // 委派型別參數用於參數與回傳值
    delegate string GenericDelegate(T value);

    class Test
    {
        static string F(int i) => "SHY520";
        static string G(string s) => "SHY520";

        static void Main(string[] args)
        {
            GenericDelegate G1 = G;
            GenericDelegate G2 = new GenericDelegate(F);
        }
    }
}

泛型委派支援回傳值與參數套用型別參數。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved