A short version of the question - why can't I do this? I am limited to .NET 3.5.
T[] genericArray;
genericArray = new T[3]{ 1.0f, 2.0f, 0.0f };
genericArray = new float[3]{ 1.0f, 2.0f, 0.0f };
The longer version is
I work with the Unity engine here, although this is not important. What is it - I am trying to transfer the conversion between its fixed Vector2 (2 floats) and Vector3 (3 floats) and my common class Vector <>. I cannot pass types directly to a shared array.
using UnityEngine;
public struct Vector<T>
{
private readonly T[] _axes;
#region Constructors
public Vector(int axisCount)
{
this._axes = new T[axisCount];
}
public Vector(T x, T y)
{
this._axes = new T[2] { x, y };
}
public Vector(T x, T y, T z)
{
this._axes = new T[3]{x, y, z};
}
public Vector(Vector2 vector2)
{
this._axes = new T[2] { vector2.x, vector2.y };
}
public Vector(Vector3 vector3)
{
this._axes = new T[3] { vector3.x, vector3.y, vector3.z };
}
#endregion
#region Properties
public T this[int i]
{
get { return _axes[i]; }
set { _axes[i] = value; }
}
public T X
{
get { return _axes[0];}
set { _axes[0] = value; }
}
public T Y
{
get { return _axes[1]; }
set { _axes[1] = value; }
}
public T Z
{
get
{
return this._axes.Length < 2 ? default(T) : _axes[2];
}
set
{
if (this._axes.Length < 2)
return;
_axes[2] = value;
}
}
#endregion
#region Type Converters
public static explicit operator Vector<T>(Vector2 vector2)
{
Vector<T> vector = new Vector<T>(vector2);
return vector;
}
public static explicit operator Vector<T>(Vector3 vector3)
{
Vector<T> vector = new Vector<T>(vector3);
return vector;
}
#endregion
}
source
share