c#编写一个表示向量(Vector)的类 ·向量的维度(Dimension)一旦确定,不可更改 。向量的长度(模,Length 提供索引器 。向量的加减法,支持与数字相加减 ·向量的点乘
时间: 2024-10-24 10:08:00 浏览: 14
在 C# 中,你可以创建一个名为 `Vector` 的类来表示二维或三维向量,确保它的属性和方法满足你所描述的要求。以下是示例代码:
```csharp
public class Vector<T>
{
private readonly int dimension;
private T[] components;
// 构造函数,限制维度不可更改
public Vector(int dimension)
{
if (dimension <= 0)
throw new ArgumentException("Dimension must be a positive integer.");
this.dimension = dimension;
components = new T[dimension];
}
// 索引器访问和修改元素
public T this[int index]
{
get => components[index];
set
{
if (index < 0 || index >= dimension)
throw new IndexOutOfRangeException();
components[index] = value;
}
}
// 计算长度(模)
public double Length()
{
double sum = 0.0;
for (int i = 0; i < dimension; i++)
sum += components[i].MultiplyBy(components[i]); // 假设有一个 MultiplyBy 方法用于计算平方
return Math.Sqrt(sum);
}
// 加法运算符
public Vector<T> operator +(Vector<T> other)
{
if (dimension != other.dimension)
throw new ArgumentException("Vectors must have the same dimension to perform addition.");
Vector<T> result = new Vector<T>(dimension);
for (int i = 0; i < dimension; i++)
result.components[i] = components[i] + other.components[i];
return result;
}
// 减法运算符
public Vector<T> operator -(Vector<T> other)
{
return this + (-other);
}
// 与数字相加减
public Vector<T> AddOrSubtract(T scalar)
{
Vector<T> vectorWithScalar = new Vector<T>(dimension);
for (int i = 0; i < dimension; i++)
vectorWithScalar.components[i] = components[i] + scalar;
return vectorWithScalar;
}
// 点乘运算
public T DotProduct(Vector<T> other)
{
if (dimension != other.dimension)
throw new ArgumentException("Vectors must have the same dimension for dot product.");
T result = default(T);
for (int i = 0; i < dimension; i++)
result += components[i] * other.components[i]; // 假设MultiplyBy方法返回的是已乘积
return result;
}
// 其他方法...
}
// 假设存在MultiplyBy方法来处理不同类型的数据
public static T MultiplyBy(this T num, T other)
{
// 根据T的类型实现乘法操作
}
```
阅读全文