C#基础(006)---泛型结构体(struct)

C# 泛型结构体(struct)

泛型在编程时相当有用,它提高了程序运行的效率,避免了拆箱与装箱的耗资源操作。

下面这个例子是一个结构体的泛型,在结构体中 定义两个泛型变量x,y 代码如下:

using System;

namespace StructEx
{
    class Program
    {
        struct Point<T>
        {
            public T x;
            public T y;
        }
        static void Main(string[] args)
        {
            //泛型为int
            Point<int> P = new Point<int>();
            P.x = 1;
            P.y = 2;
            Console.WriteLine(P.x.ToString() + " " + P.y.ToString());

            //泛型为Array
            Point<Array> PP = new Point<Array>();
            string p1 = "sahfs";
            PP.x = p1.ToCharArray();
            foreach (char cc in PP.x)
            {
                Console.WriteLine(cc);
            }
            Console.Read();

        }
    }
}
结构体中定义的变量,在类中引用的时候,可以随时更改其类型,操作方便,无须重复定义

运行结构如下: 

 
 

posted on 2014-04-19 23:03  lbsf  阅读(2752)  评论(0)    收藏  举报

导航