泛型是由2.0引进来的,有了泛型,就不再使用object类了。泛型相当于c++中的模板,泛型是C#语言的一个结构而且是CLR定义的。泛型的最大优点就是提高了性能,减少了值类型和引用类型的拆箱和装箱。

8.1 创建泛型类

 创建泛型类和定义一般类类似,只是要使用泛型类型声明。下面给出例子:

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

namespace GenericDemo
{
    
//泛型
    public class LinkedListNode<T>
    {
        
public LinkedListNode(T value)
        {
            
this.value = value;
        }

        
private T value;
        
public T Value
        {
            
get { return value; }
        }

        
private LinkedListNode<T> next;
        
public LinkedListNode<T> Next
        {
            
get { return next; }
            
internal set { next = value; }
        }

        
private LinkedListNode<T> prev;
        
public LinkedListNode<T> Prev
        {
            
get { return prev; }
            
internal set { prev = value; }
        }

    }

    
public class LinkedList<T> : IEnumerable<T>
    {
        
private LinkedListNode<T> first;

        
public LinkedListNode<T> First
        {
            
get { return first; }
        }

        
private LinkedListNode<T> last;

        
public LinkedListNode<T> Last
        {
            
get { return last; }
        }

        
//添加
        public LinkedListNode<T> AddLast(T node)
        {
            LinkedListNode
<T> newNode = new LinkedListNode<T>(node);
            
if (first == null)
            {
                first 
= newNode;
                last 
= first;
            }
            
else
            {
                last.Next 
= newNode;
                last 
= newNode;
            }
            
return newNode;
        }



        
#region IEnumerable<T> Members

        
public IEnumerator<T> GetEnumerator()
        {
            LinkedListNode
<T> current = first;

            
while (current != null)
            {
                
yield return current.Value;
                current 
= current.Next;
            }
        }

        
#endregion

        
#region IEnumerable Members

        
//返回枚举值
        IEnumerator IEnumerable.GetEnumerator()
        {
            
return GetEnumerator();

        }

        
#endregion
    }
    
class Program
    {
        
static void Main(string[] args)
        {
            
//所使用泛型
            LinkedList<int> list2 = new LinkedList<int>();
            list2.AddLast(
3);
            list2.AddLast(
5);
            list2.AddLast(
7);

            
foreach (int i in list2)
            {
                Console.WriteLine(i);
            }

        }
    }
}

相关文章:

  • 2021-09-29
  • 2021-09-27
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-16
  • 2022-12-23
  • 2022-03-09
猜你喜欢
  • 2022-01-22
  • 2022-02-02
  • 2022-03-02
  • 2021-10-08
  • 2021-06-20
  • 2021-06-17
  • 2022-01-24
相关资源
相似解决方案