将特定类型对象赋值到泛型数组中
本文关键字:泛型 数组 赋值 对象 类型 | 更新日期: 2023-09-27 18:02:38
我有一个通用类型Vector<T>
,我这样创建它,因为T
可能是float
或Complex
:
public class Vector<T>
{
#region Properties
public ulong Length
{
get
{
return _length;
}
}
public VectorType VectorType
{
get
{
return _vectorType;
}
}
#endregion
#region Indexers
public T this[ulong index]
{
get
{
return _data[index];
}
set
{
_data[index] = value;
}
}
#endregion
#region Constructors
public Vector(VectorType vectorType, T[] data)
{
if (!((data is float[]) || (data is Complex[])))
{
throw new InvalidDataException("Data must be array of float or array of Complex");
}
_data = new T[_length = (ulong)data.Length];
for (ulong i = 0; i < _length; i++)
{
_data[i] = data[i];
}
_vectorType = vectorType;
}
public Vector(VectorType vectorType, Vector<T> vector)
{
_data = new T[_length = vector.Length];
for (ulong i = 0; i < _length; i++)
{
_data[i] = vector[i];
}
_vectorType = vectorType;
}
#endregion
#region Methods
//Unity Matrix, this vector has 1/N everywhere
public static Vector<float> e(VectorType vectorType, ulong length)
{
var data = new float[length];
for (ulong i = 0; i < length; i++)
{
data[i] = (float)1 / length;
}
var vectorE = new Vector<float>(vectorType, data);
return vectorE;
}
public float Sum()
{
float sum = 0;
if (_data is float[])
{
sum = (_data as float[]).Sum();
}
else
{
if (_data is Complex[])
{
for (ulong i = 0; i < _length; i++)
{
sum += (float)
Math.Sqrt(Math.Pow((_data[i] as Complex?).Value.Real, 2) +
Math.Pow((_data[i] as Complex?).Value.Imaginary, 2));
}
}
}
return sum;
}
public bool CheckIfSochasitc()
{
return Math.Abs(Sum() - 1) < float.Epsilon;
}
public void Normalize()
{
var sum = Sum();
if (_data is float[])
{
for (ulong i = 0; i < _length; i++)
{
float x = ((float) _data[i])/sum;
_data[i] = (T)x;
}
}
}
#endregion
#region Operators
//I omitted the code inhere to avoid overload
#endregion
#region Fields
private ulong _length;
private readonly VectorType _vectorType;
private T[] _data;
#endregion
}
public enum VectorType
{
Row,Column
}
我的问题是,我有一个通用数组(如果我可以这样称呼它):
private T[] _data;
还有Normalize()方法:
public void Normalize()
{
var sum = Sum();
if (_data is float[])
{
for (ulong i = 0; i < _length; i++)
{
//Here is the problem
_data[i] = ((_data[i] as float?) / sum);
}
}
}
这不起作用说can't cast float to T
试图搜索,但找不到有用的助手,任何澄清我都很感激。
更新:
Sum()方法总是返回浮点数
不清楚为什么要转换为float?
(或者为什么要使用ulong
作为索引变量类型…),但您只需要将结果转换回T
-否则您不能将其分配回T[]
类型的数组。此外,您需要强制转换为object
(为了转换回T
):
float x = ((float) (object) data[i]) / sum;
data[i] = (T) (object) x;
您可以在第一行使用float?
和as
,以避免装箱-但是您需要获得非空值:
float x = (data[i] as float?).Value / sum;
都很难看:(
)正如在注释中提到的那样,这种事情通常表明设计根本没有真正正确地通用。我们不知道Sum()
返回的是什么类型,但是您应该考虑您的类型开头有多"通用"。
也许你可以试试这个
if (typeof(_data) == float[])
{
for (ulong i = 0; i < _length; i++)
{
_data[i] = ((_data[i] as float?) / sum);
}
}