首先,我目前正在使用VB.NET,因此对C#并不是很了解.
我想创建一个带有约束的定制泛型向量类,即类型参数必须实现接口INumber(Of T).然而,当我试图在所述类中声明+-operator(使用由两个向量给出的值的元素相加)时,我的VB.NET项目产生了以下错误:
错误BC30452没有为类型‘T’和‘T’定义运算符‘+’
因为我几乎只测试了this page上给出的例子,并不真的相信微软会发布一些不起作用的东西,所以我决定也用C#(也使用.NET7)来测试我的问题.
为此,我在VB.NET年内建立了两个MWE
Vector.vb:
Imports System.Numerics
Public Class Vector(Of T As INumber(Of T))
Private _items() As T
Public Sub New(n As Integer)
ReDim _items(n - 1)
End Sub
Public ReadOnly Property Size As Integer
Get
Return _items.Length
End Get
End Property
Public Function GetValue(i As Integer) As T
Return _items(i)
End Function
Public Sub SetValue(i As Integer, val As T)
_items(i) = val
End Sub
Public Sub SetAll(val As T)
For i As Integer = 0 To _items.Length - 1
_items(i) = val
Next
End Sub
Public Sub Print()
For i As Integer = 0 To _items.Length - 1
Console.WriteLine(_items(i))
Next
End Sub
Public Shared Operator +(a As Vector(Of T), b As Vector(Of T)) As Vector(Of T)
Dim retVal As New Vector(Of T)(a.Size)
For i As Integer = 0 To retVal.Size - 1
retVal.SetValue(i, a.GetValue(i) + b.GetValue(i))
Next
Return retVal
End Operator
End Class
Program.vb:
Module Program
Sub Main(args As String())
Dim x As New Vector(Of Double)(3)
x.SetAll(3)
Dim y As New Vector(Of Double)(3)
y.SetAll(2)
Dim z = x + y
z.Print()
End Sub
End Module
在C#年内
Vector.cs:
using System.Numerics;
namespace Test
{
public class Vector<T> where T : INumber<T>
{
private T[] _items;
public Vector(int n) {
Array.Resize<T>(ref _items, n);
}
public int Size {
get { return _items.Length; }
}
public T GetValue(int i) {
return _items[i];
}
public void SetValue(int i, T val){
_items[i] = val;
}
public void SetAll(T val) {
for (var i = 0; i < _items.Length; i++) {
_items[i] = val;
}
}
public void Print() {
for (var i = 0; i < _items.Length; i++) {
Console.WriteLine(_items[i]);
}
}
public static Vector<T> operator +(Vector<T> a, Vector<T> b)
{
var retVal = new Vector<T>(a.Size);
for (var i = 0; i < retVal.Size; i++) {
retVal.SetValue(i, a.GetValue(i) + b.GetValue(i));
}
return retVal;
}
}
}
Program.cs:
using Test;
var x = new Vector<Double>(3);
x.SetAll(3);
var y = new Vector<Double>(3);
y.SetAll(2);
var z = x + y;
z.Print();
在每个MWE中,创建长度为3的两个向量(双倍)x,y,使得x的所有条目都是3,y的所有条目都是2.然后将这些向量相加并保存在向量z中.
C#项目编译时没有出现错误,并生成以下输出
5
5
5
while the VB.NET project won't compile and throws above mentioned error.
I don't even really understand why the error is thrown in the first place. The type parameter was given the constrain, that it has to implement the interface INumber(Of T), which in return implements the IAdditionOperators(Of T,T,T) interface, which in return exposes the +-operator. I therefore thought, that T should be able to rely on said operator, like it does in C#, but not in VB.NET.
Is that an error on my site or is VB.NET not working correctly in that regard?