C#中3维向量的实现

c#中默认不带库三维向量,需要自己安装第三方库,或者可以手动实现一个简易的三维向量。

cs 复制代码
public struct Vector3D
{
    public double X { get; set; }
    public double Y { get; set; }
    public double Z { get; set; }

    public Vector3D(double x, double y, double z)
    {
        X = x;
        Y = y;
        Z = z;
    }

    //--- 运算符重载 ---
    // 向量加法
    public static Vector3D operator +(Vector3D a, Vector3D b)
    {
        return new Vector3D(a.X + b.X, a.Y + b.Y, a.Z + b.Z);
    }

    // 向量减法
    public static Vector3D operator -(Vector3D a, Vector3D b)
    {
        return new Vector3D(a.X - b.X, a.Y - b.Y, a.Z - b.Z);
    }

    // 向量标量乘法(向量 * 标量)
    public static Vector3D operator *(Vector3D v, double scalar)
    {
        return new Vector3D(v.X * scalar, v.Y * scalar, v.Z * scalar);
    }

    // 向量标量乘法(标量 * 向量)
    public static Vector3D operator *(double scalar, Vector3D v)
    {
        return v * scalar; // 复用上述实现
    }

    // 向量标量除法(向量 / 标量)
    public static Vector3D operator /(Vector3D v, double scalar)
    {
        if (Math.Abs(scalar) < double.Epsilon)
            throw new DivideByZeroException("标量不能为零!");
        
        return new Vector3D(v.X / scalar, v.Y / scalar, v.Z / scalar);
    }

    //--- 其他方法 ---
    // 向量点积
    public static double Dot(Vector3D a, Vector3D b)
    {
        return a.X * b.X + a.Y * b.Y + a.Z * b.Z;
    }

    // 向量叉积
    public static Vector3D Cross(Vector3D a, Vector3D b)
    {
        return new Vector3D(
            a.Y * b.Z - a.Z * b.Y,
            a.Z * b.X - a.X * b.Z,
            a.X * b.Y - a.Y * b.X
        );
    }

    // 向量长度
    public double Length()
    {
        return Math.Sqrt(X * X + Y * Y + Z * Z);
    }

    // 向量归一化(单位化)
    public Vector3D Normalize()
    {
        double length = Length();
        if (length < double.Epsilon)
            throw new InvalidOperationException("零向量无法归一化!");
        
        return this / length; // 使用标量除法运算符
    }

    // 重写 ToString
    public override string ToString()
    {
        return $"({X:F3}, {Y:F3}, {Z:F3})";
    }
}
相关推荐
hez20101 天前
在 .NET 上构建超大托管数组
c#·.net·.net core·gc·clr
雨落倾城夏未凉6 天前
第四章c#方法-参数数组和可选参数(16)
后端·c#
唐青枫7 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫8 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m6258 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户91721561902118 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠9 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
唐青枫11 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech12 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf13 天前
C#摸鱼实录——IoC与DI案例详解
c#