У меня есть проблема, которая, я надеюсь, является простым решением. У меня есть следующий класс (выдержка), и я бы хотел избежать создания public myImage(myImage<int> image)
, public myImage(myImage<float> image)
, public myImage(myImage<double> image)
и других возможных вариантов (например, bool).
class myImage<T> where T : struct
{
private int width;
private int height;
private T[] img;
// constructor: allocate new image
public myImage(int Width, int Height)
{
img = new T[Width*Height];
width = Width;
height = Height;
}
public myImage(myImage<byte> image)
{
// allocate space for new
width = image.Width;
height = image.Height;
img = new T[width * height];
if (typeof(T) == typeof(byte))
{
// in and out = same type? use block copy
Buffer.BlockCopy(image.Image, 0, img, 0, width * height * Marshal.SizeOf(typeof(T)));
}
else
{
// else copy image element by element
for (int counter = 0; counter < width * height; counter++)
img[counter] = (T)Convert.ChangeType(image[counter], typeof(T));
}
}
public int Width
{
get { return width; }
}
public int Height
{
get { return height; }
}
public T[] Image
{
get { return img; }
}
public Object this[int index]
{
get { return img[index]; }
set { img[index] = (T)Convert.ChangeType(value, typeof(T)); }
}
}
Я бы использовал это так:
myImage<byte> img = new myImage<byte>(100,200); // create byte image
myImage<double> img2 = new myImage<double>(img); // create double-img2 from byte-img
myImage<int> img3 = new myImage<int>(img2); // or int-img3 from double-img2
Итак, мне нужно создавать методы для byte, int, float, double или 1 метод может делать все это?