型別參數(type parameter): Dictionary<TKey,TValue>的型別參數就是 TKey 及 TValue.

泛型型別(generic type):包含類別`介面`委派還有結構,但列舉並不支援.又分為非約束泛型型別和建構式型別.

非約束泛型型別(unbound generic type):型別參數並未指定任何的型別.

建構式型別(constructed type):型別參數已經有指定其他的型別.

非約束泛型型別可衍生出建構式型別.

建構式型別分成 1.開放型別(open type)2.封閉型別(close type).

開放型別:public class Subclass<T,S> :Dictionary<T,string>{..}.

封閉型別:public class Subclass<T,S> :Dictionary<int,string>{..}.

泛型介面:  IList<(Of <(T>)>) ,IEquatable<(Of <(T>)>).

 // 如果是類別的實作方式

    public class MyClass
    {
        public object Source { get; set; }
    }
 
    public class MyClass<T> : MyClass
    {
        public new T Source { get; set; } // 用new將object改成回傳T
    }
 
    // 如果是介面的的實作方式
    public interface MyInterface
    {
        object Source { get; set; }
    }
 
    public class MyInterface<T> : MyInterface
    {
        public T Source { get; set; }
 
        object MyInterface.Source // 實作私有介面
        {
            get 
            {
                return this.Source;
            }
            set
            {
                this.Source = (T)value;
            }
        }
    }
泛型方法: List<TOutput> ConverAll<TOutput>(Converter<T,TOutput> conv)
        List<Guid> ConverAll<Guid>(Converter<string,Guid> conv)  
  •  
    • 方法會回傳一個List<Guid>.
    • 方法名稱為ConverAll.
    • 方法只有一型別參數指定為Guid.
    • 此方法只有一個參數,參數名稱為conv,他是屬於Converter<string,Guid>的泛型型別.

                      Converter<string,Guid>是一個泛型的委派型別(geneic delegate type),

                      方法的簽章:public Guid MyConverter(string convertString){...}

 static void Main(string[] args)
        {
            List<int> integers = new List<int>();
            integers.Add(1);
            integers.Add(2);
            integers.Add(3);
            integers.Add(4);
           // Converter<int, double> conv = TaskSquareRoot;
            Converter<int, double> conv2 = (x) => { return Math.Sqrt(x); }; //Lambda
            List<double> doubles;
            //doubles = integers.ConvertAll(conv);
            doubles = integers.ConvertAll(conv2); 
        
            foreach (double d in doubles)
            {
                Console.WriteLine(d);
            }
            Console.ReadLine();
        }
        static double TaskSquareRoot(int x) //方法的簽章
        {
            return Math.Sqrt(x);
        }

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 linear 的頭像
    linear

    李泥兒

    linear 發表在 痞客邦 留言(0) 人氣()