zoukankan      html  css  js  c++  java
  • 复习泛型(一)

    泛型类和泛型方法同时具备可重用性、类型安全和效率,这是非泛型类和非泛型方法无法具备的。泛型通常用在集合和在集合上运行的方法中。.NET Framework 2.0 版类库提供一个新的命名空间 System.Collections.Generic,其中包含几个新的基于泛型的集合类。建议面向 2.0 版的所有应用程序都使用新的泛型集合类,而不要使用旧的非泛型集合类,如 ArrayList。有关更多信息,请参见 .NET Framework 类库中的泛型(C# 编程指南)

    当然,也可以创建自定义泛型类型和方法,以提供自己的通用解决方案,设计类型安全的高效模式。下面的代码示例演示一个用于演示用途的简单泛型链接列表类。(大多数情况下,建议使用 .NET Framework 类库提供的 List<T> 类,而不要自行创建类。)在通常使用具体类型来指示列表中所存储项的类型时,可使用类型参数 T。自定义简单泛型列表类方法如下:

    // type parameter T in angle brackets
    public class GenericList<T> 
    {
        // The nested class is also generic on T
        private class Node
        {
            // T used in non-generic constructor
            public Node(T t)
            {
                next = null;
                data = t;
            }
    
            private Node next;
            public Node Next
            {
                get { return next; }
                set { next = value; }
            }
            
            // T as private member data type
            private T data;
    
            // T as return type of property
            public T Data  
            {
                get { return data; }
                set { data = value; }
            }
        }
    
        private Node head;
        
        // constructor
        public GenericList() 
        {
            head = null;
        }
    
        // T as method parameter type:
        public void AddHead(T t) 
        {
            Node n = new Node(t);
            n.Next = head;
            head = n;
        }
    
        public IEnumerator<T> GetEnumerator()
        {
            Node current = head;
    
            while (current != null)
            {
                yield return current.Data;
                current = current.Next;
            }
        }
    }

    使用改泛型列表类:

    class TestGenericList
    {
        static void Main()
        {
            // int is the type argument
            GenericList<int> list = new GenericList<int>();
    
            for (int x = 0; x < 10; x++)
            {
                list.AddHead(x);
            }
    
            foreach (int i in list)
            {
                System.Console.Write(i + " ");
            }
            System.Console.WriteLine("\nDone");
        }
    }

    类型参数命名准则

    1、务必使用描述性名称命名泛型类型参数,除非单个字母名称完全可以让人了解它表示的含义,而描述性名称不会有更多的意义。

    public interface ISessionChannel<TSession> { /*...*/ }
    public delegate TOutput Converter<TInput, TOutput>(TInput from);
    public class List<T> { /*...*/ }
    

    2、考虑使用 T 作为具有单个字母类型参数的类型的类型参数名。

    public int IComparer<T>() { return 0; }
    public delegate bool Predicate<T>(T item);
    public struct Nullable<T> where T : struct { /*...*/ }

    3、务必将“T”作为描述性类型参数名的前缀。

    public interface ISessionChannel<TSession>
    {
        TSession Session { get; }
    }

    类型参数的约束

    在定义泛型类时,可以对客户端代码能够在实例化类时用于类型参数的类型种类施加限制。如果客户端代码尝试使用某个约束所不允许的类型来实例化类,则会产生编译时错误。这些限制称为约束。约束是使用 where 上下文关键字指定的。下表列出了六种类型的约束:

    约束说明

    T:结构

    类型参数必须是值类型。可以指定除 Nullable 以外的任何值类型。有关更多信息,请参见使用可空类型(C# 编程指南)

    T:类

    类型参数必须是引用类型,包括任何类、接口、委托或数组类型。

    T:new()

    类型参数必须具有无参数的公共构造函数。当与其他约束一起使用时,new() 约束必须最后指定。

    T:<基类名>

    类型参数必须是指定的基类或派生自指定的基类。

    T:<接口名称>

    类型参数必须是指定的接口或实现指定的接口。可以指定多个接口约束。约束接口也可以是泛型的。

    T:U

    为 T 提供的类型参数必须是为 U 提供的参数或派生自为 U 提供的参数。这称为裸类型约束。

    如果要检查泛型列表中的某个项以确定它是否有效,或者将它与其他某个项进行比较,则编译器必须在一定程度上保证它需要调用的运算符或方法将受到客户端代码可能指定的任何类型参数的支持。这种保证是通过对泛型类定义应用一个或多个约束获得的。例如,基类约束告诉编译器:仅此类型的对象或从此类型派生的对象才可用作类型参数。一旦编译器有了这个保证,它就能够允许在泛型类中调用该类型的方法。约束是使用上下文关键字 where 应用的。下面的代码示例演示可通过应用基类约束添加到GenericList<T> 类(在泛型介绍(C# 编程指南)中)的功能。

    View Code
    public class Employee
    {
        private string name;
        private int id;
    
        public Employee(string s, int i)
        {
            name = s;
            id = i;
        }
    
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
    
        public int ID
        {
            get { return id; }
            set { id = value; }
        }
    }
    
    public class GenericList<T> where T : Employee
    {
        private class Node
        {
            private Node next;
            private T data;
    
            public Node(T t)
            {
                next = null;
                data = t;
            }
    
            public Node Next
            {
                get { return next; }
                set { next = value; }
            }
    
            public T Data
            {
                get { return data; }
                set { data = value; }
            }
        }
    
        private Node head;
    
        public GenericList() //constructor
        {
            head = null;
        }
    
        public void AddHead(T t)
        {
            Node n = new Node(t);
            n.Next = head;
            head = n;
        }
    
        public IEnumerator<T> GetEnumerator()
        {
            Node current = head;
    
            while (current != null)
            {
                yield return current.Data;
                current = current.Next;
            }
        }
    
        public T FindFirstOccurrence(string s)
        {
            Node current = head;
            T t = null;
    
            while (current != null)
            {
                //The constraint enables access to the Name property.
                if (current.Data.Name == s)
                {
                    t = current.Data;
                    break;
                }
                else
                {
                    current = current.Next;
                }
            }
            return t;
        }
    }

    泛型接口

    为泛型集合类或表示集合中项的泛型类定义接口通常很有用。对于泛型类,使用泛型接口十分可取,例如使用 IComparable<T> 而不使用 IComparable,这样可以避免值类型的装箱和取消装箱操作。.NET Framework 2.0 类库定义了若干新的泛型接口,以用于 System.Collections.Generic 命名空间中新的集合类。

    将接口指定为类型参数的约束时,只能使用实现此接口的类型。下面的代码示例显示从 GenericList<T> 类派生的 SortedList<T> 类

    SortedList<T> 添加了约束 where T : IComparable<T>。这将使 SortedList<T> 中的 BubbleSort 方法能够对列表元素使用泛型 CompareTo 方法。在此示例中,列表元素为简单类,即实现 IComparable<Person> 的 Person

    View Code
    //Type parameter T in angle brackets.
    public class GenericList<T> : System.Collections.Generic.IEnumerable<T>
    {
        protected Node head;
        protected Node current = null;
    
        // Nested class is also generic on T
        protected class Node
        {
            public Node next;
            private T data;  //T as private member datatype
    
            public Node(T t)  //T used in non-generic constructor
            {
                next = null;
                data = t;
            }
    
            public Node Next
            {
                get { return next; }
                set { next = value; }
            }
    
            public T Data  //T as return type of property
            {
                get { return data; }
                set { data = value; }
            }
        }
    
        public GenericList()  //constructor
        {
            head = null;
        }
    
        public void AddHead(T t)  //T as method parameter type
        {
            Node n = new Node(t);
            n.Next = head;
            head = n;
        }
    
        // Implementation of the iterator
        public System.Collections.Generic.IEnumerator<T> GetEnumerator()
        {
            Node current = head;
            while (current != null)
            {
                yield return current.Data;
                current = current.Next;
            }
        }
    
        // IEnumerable<T> inherits from IEnumerable, therefore this class 
        // must implement both the generic and non-generic versions of 
        // GetEnumerator. In most cases, the non-generic method can 
        // simply call the generic method.
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
    
    public class SortedList<T> : GenericList<T> where T : System.IComparable<T>
    {
        // A simple, unoptimized sort algorithm that 
        // orders list elements from lowest to highest:
    
        public void BubbleSort()
        {
            if (null == head || null == head.Next)
            {
                return;
            }
            bool swapped;
    
            do
            {
                Node previous = null;
                Node current = head;
                swapped = false;
    
                while (current.next != null)
                {
                    //  Because we need to call this method, the SortedList
                    //  class is constrained on IEnumerable<T>
                    if (current.Data.CompareTo(current.next.Data) > 0)
                    {
                        Node tmp = current.next;
                        current.next = current.next.next;
                        tmp.next = current;
    
                        if (previous == null)
                        {
                            head = tmp;
                        }
                        else
                        {
                            previous.next = tmp;
                        }
                        previous = tmp;
                        swapped = true;
                    }
                    else
                    {
                        previous = current;
                        current = current.next;
                    }
                }
            } while (swapped);
        }
    }
    
    // A simple class that implements IComparable<T> using itself as the 
    // type argument. This is a common design pattern in objects that 
    // are stored in generic lists.
    public class Person : System.IComparable<Person>
    {
        string name;
        int age;
    
        public Person(string s, int i)
        {
            name = s;
            age = i;
        }
    
        // This will cause list elements to be sorted on age values.
        public int CompareTo(Person p)
        {
            return age - p.age;
        }
    
        public override string ToString()
        {
            return name + ":" + age;
        }
    
        // Must implement Equals.
        public bool Equals(Person p)
        {
            return (this.age == p.age);
        }
    }
    
    class Program
    {
        static void Main()
        {
            //Declare and instantiate a new generic SortedList class.
            //Person is the type argument.
            SortedList<Person> list = new SortedList<Person>();
    
            //Create name and age values to initialize Person objects.
            string[] names = new string[] 
            { 
                "Franscoise", 
                "Bill", 
                "Li", 
                "Sandra", 
                "Gunnar", 
                "Alok", 
                "Hiroyuki", 
                "Maria", 
                "Alessandro", 
                "Raul" 
            };
    
            int[] ages = new int[] { 45, 19, 28, 23, 18, 9, 108, 72, 30, 35 };
    
            //Populate the list.
            for (int x = 0; x < 10; x++)
            {
                list.AddHead(new Person(names[x], ages[x]));
            }
    
            //Print out unsorted list.
            foreach (Person p in list)
            {
                System.Console.WriteLine(p.ToString());
            }
            System.Console.WriteLine("Done with unsorted list");
    
            //Sort the list.
            list.BubbleSort();
    
            //Print out sorted list.
            foreach (Person p in list)
            {
                System.Console.WriteLine(p.ToString());
            }
            System.Console.WriteLine("Done with sorted list");
        }
    }

    类之间的继承规则同样适用于接口

    泛型方法

    泛型方法是使用类型参数声明的方法,如下所示:

    static void Swap<T>(ref T lhs, ref T rhs)
    {
        T temp;
        temp = lhs;
        lhs = rhs;
        rhs = temp;
    }

    调用:

    public static void TestSwap()
    {
        int a = 1;
        int b = 2;
    
        Swap<int>(ref a, ref b);
        System.Console.WriteLine(a + " " + b);
    }

    在泛型类中,非泛型方法可以访问类级别类型参数,如下

    class SampleClass<T>
    {
        void Swap(ref T lhs, ref T rhs) { }
    }

    使用约束对方法中的类型参数启用更专门的操作。此版本的 Swap<T> 现在称为 SwapIfGreater<T>,它只能与实现 IComparable<T> 的类型参数一起使用

    void SwapIfGreater<T>(ref T lhs, ref T rhs) where T : System.IComparable<T>
    {
        T temp;
        if (lhs.CompareTo(rhs) > 0)
        {
            temp = lhs;
            lhs = rhs;
            rhs = temp;
        }
    }
  • 相关阅读:
    使用了Theme但是没有效果问题
    4.0 流量控制preference
    android sdk国内目录http://mirrors.neusoft.edu.cn/android/repository/
    xmpp push篇一 广播消息
    cursorfilter
    android 特效UI实现
    Android四大组件一----Activity
    net user命令
    sql2005如何附加数据库
    sql2005中如何启用SA账号
  • 原文地址:https://www.cnblogs.com/xiepeixing/p/2854952.html
Copyright © 2011-2022 走看看