主页 > 知识库 > 网络编程 > ASP/.NET >

.NET 数据类型之指针类型(2)

来源:中国IT实验室 作者:佚名 发表于:2013-07-15 16:06  点击:
代码示例 指针访问成员 struct CoOrds { public int x; public int y;}class AccessMembers{ static void Main(){ CoOrds home; unsafe { CoOrds* p = home; p-x = 25; p-y = 12; System.Console.WriteLine(The coo

代码示例指针访问成员
struct CoOrds
{    public int x;    public int y;}class AccessMembers{    static void Main()
{
   CoOrds home;
   unsafe
    {

  CoOrds* p = &home;

  p->x = 25;

  p->y = 12;

  System.Console.WriteLine("The coordinates are: x={0}, y={1}", p->x, p->y );
   }    }}
指针访问数组元素
class Pointers{    unsafe static void Main()
{
   char* charPointer = stackalloc char[123];
   for (int i = 65; i < 123; i++)
   {

  charPointer[i] = (char)i;
   }
   System.Console.WriteLine("Uppercase letters:");
   for (int i = 65; i < 91; i++)
   {

  System.Console.Write(charPointer[i]);
   }
   System.Console.WriteLine();
   System.Console.WriteLine("Lowercase letters:");
   for (int i = 97; i < 123; i++)
   {

  System.Console.Write(charPointer[i]);
   }    }}
指针复制字节数组
class TestCopy{    static unsafe void Copy(byte[] src, int srcIndex, byte[] dst, int dstIndex, int count)    {
   if (src == null || srcIndex < 0 ||

  dst == null || dstIndex < 0 || count < 0)
   {

  throw new System.ArgumentException();
   }
   int srcLen = src.Length;
   int dstLen = dst.Length;
   if (srcLen - srcIndex < count || dstLen - dstIndex < count)
   {

  throw new System.ArgumentException();
   }
   fixed (byte* pSrc = src, pDst = dst)
   {

  byte* ps = pSrc;

  byte* pd = pDst;

  for (int i = 0 ; i < count / 4 ; i++)

  {


 *((int*)pd) = *((int*)ps);


 pd += 4;


 ps += 4;

  }

  for (int i = 0; i < count % 4 ; i++)

  {


 *pd = *ps;


 pd++;


 ps++;

  }
   }    }    static void Main()    {
   byte[] a = new byte[100];
   byte[] b = new byte[100];
   for (int i = 0; i < 100; ++i)
   {

  a[i] = (byte)i;
   }
   Copy(a, 0, b, 0, 100);
   System.Console.WriteLine("The first 10 elements are:");
   for (int i = 0; i < 10; ++i)
    {

  System.Console.Write(b[i] + " ");
   }
   System.Console.WriteLine("/n");    }}

有帮助
(0)
0%
没帮助
(0)
0%