我有一个名为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
答案 0 :(得分:4)
不清楚为什么你要转换为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()
返回什么类型,但您应该考虑如何&#34; general&#34;你的类型是从一开始。
答案 1 :(得分:-2)
可能你可以试试这个
if (typeof(_data) == float[])
{
for (ulong i = 0; i < _length; i++)
{
_data[i] = ((_data[i] as float?) / sum);
}
}