我不確定這是否可能,但如果是,那么它會很有用。
我正在嘗試在一個名為Matrix<T>. 目的是能夠擁有各種資料型別的矩陣,例如整數、浮點數、雙精度數等。
我現在想定義加法:
public static Matrix<T> operator (Matrix<T> first, Matrix<T> second)
{
if (first.dimension != second.dimension)
{
throw new Exception("The matrices' dimensions do not match");
}
Matrix<T> add = new Matrix<T>(first.dimension);
for (int i = 1; i <= first.rows; i )
{
for (int j = 1; j <= first.columns; i )
{
add[i,j] = first[i,j] second[i,j];
}
}
return add;
}
該行存在問題,add[i,j] = first[i,j] second[i,j];因為該操作 未在型別為 的常規物件上定義T。
我只想指定矩陣 whereT是一個型別,以便定義加法,但是。所以,我可以制作一個由ints、floats、doubles 等組成的矩陣,但是如果我要嘗試定義一個矩陣,比如int[]s,我希望它拋出一個例外,因為 沒有為int[]s定義。
所以,不是寫T,有什么方法可以告訴計算機“這可以接受任何泛型型別,只要 在型別上定義了一個運算子?或者,這是不可能的,我將不得不單獨定義一個矩陣ints、s 的矩陣float等等?
編輯:我沒有看到閉包中的鏈接問題與此有什么關系-我對那里的操作員一無所知。如果它們相關,有人可以解釋一下嗎?
uj5u.com熱心網友回復:
目前,它是不可能的(至少不失編譯時的安全性或更改API),但預覽功能啟用,System.Runtime.Experimental的NuGet可以使用IAdditionOperators限制T有 運營商定義的。我想說將這個介面也添加到Matrix它本身是一個好主意:
class Matrix<T> : IAdditionOperators<Matrix<T>, Matrix<T>, Matrix<T>> where T : IAdditionOperators<T, T, T>
{
public static Matrix<T> operator (Matrix<T> left, Matrix<T> right)
{
// swap to real implementation here
T x = default;
T y = default;
Console.WriteLine(x y);
return default;
}
}
也可以看看:
- 通用數學(尤其是有關嘗試的部分,請注意 - 推薦使用 VS 2022)
uj5u.com熱心網友回復:
可以使用反射
class Int
{
readonly int v;
public int Get => v;
public Int(int v)
{
this.v = v;
}
public static Int operator (Int me, Int other) => new Int(me.v other.v);
}
class Arr<T>
{
T[] _arr;
public Arr(T[] arr)
{
_arr = arr;
}
public T this[int index] => _arr[index];
public static Arr<T> operator (Arr<T> me, Arr<T> other)
{
var addMethod = typeof(T).GetMethod("op_Addition");
if (addMethod == null)
throw new InvalidOperationException($"Type {typeof(T)} doesn't implement ' ' operator");
var result = me._arr.Zip(other._arr)
.Select(elements => addMethod.Invoke(null, new object[] { elements.First, elements.Second }))
.Cast<T>()
.ToArray();
return new Arr<T>(result);
}
}
[Test]
public void TestAdd()
{
var firstArray = new Arr<Int>(new[] { new Int(1), new Int(2) });
var secondArray = new Arr<Int>(new[] { new Int(2), new Int(3) });
var sum = firstArray secondArray;
Assert.AreEqual(3, sum[0].Get);
Assert.AreEqual(5, sum[1].Get);
}
將示例簡化為陣列。不幸的是,即使 T 沒有實作 add 運算子,它也會編譯,因此您將在運行時遇到例外。您還可以檢查 add 方法是否具有正確的簽名(回傳 T 并采用兩個 T)。如果您需要幫助理解代碼,請告訴我!
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/361538.html
上一篇:如何計算給定點周圍的面積
