在C#中,Struct
是一种值类型,用于表示一组相关的数据。它们通常用于表示轻量级对象,例如点、矩形、颜色等。以下是关于C#中Struct的一些常见技巧:
public struct Point
{
public int X;
public int Y;
}
Point point;
point.X = 10;
point.Y = 20;
public struct Point
{
public int X;
public int Y;
public Point(int x, int y)
{
X = x;
Y = y;
}
}
Point point = new Point(10, 20);
ref
关键字传递Struct参数:public struct Point
{
public int X;
public int Y;
}
public static void Swap(ref Point a, ref Point b)
{
Point temp = a;
a = b;
b = temp;
}
Point point1 = new Point { X = 10, Y = 20 };
Point point2 = new Point { X = 30, Y = 40 };
Swap(ref point1, ref point2);
in
关键字优化性能:public struct Point
{
public int X;
public int Y;
}
public static void Print(in Point point)
{
Console.WriteLine($"X: {point.X}, Y: {point.Y}");
}
Point point = new Point { X = 10, Y = 20 };
Print(point);
readonly
关键字创建只读Struct:public readonly struct Point
{
public int X { get; }
public int Y { get; }
public Point(int x, int y)
{
X = x;
Y = y;
}
}
Point point = new Point(10, 20);
System.Runtime.InteropServices.StructLayout
属性控制Struct的内存布局:using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
public struct Point
{
public int X;
public int Y;
}
System.Runtime.InteropServices.Marshal
类将Struct转换为其他数据类型:using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
public struct Point
{
public int X;
public int Y;
}
Point point = new Point { X = 10, Y = 20 };
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(point));
Marshal.StructureToPtr(point, ptr, false);
Point newPoint = (Point)Marshal.PtrToStructure(ptr, typeof(Point));
Marshal.FreeHGlobal(ptr);
以上就是关于C#中Struct的一些常见技巧。