c# - 使用与创建类不同的泛型类型调用构造函数

标签 c# generics constructor

我有这个问题,我希望它是一个简单的解决方案。我有以下类(class)(摘录),我想避免制作 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 创建方法,还是一种方法可以完成所有工作?

最佳答案

你不能在构造函数中使用泛型参数,但你可以像这样定义一个静态方法:

class myImage<T> where T : struct {

    public static myImage<T> FromImage<X>(myImage<X> image) where X : struct {
        // create the object and return it...
    }
}

然后像这样调用它

myImage<double> img2 = myImage<double>.FromImage<byte>(img);

关于c# - 使用与创建类不同的泛型类型调用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7432394/

相关文章:

constructor - Kotlin:如何避免构造函数中的代码重复?

c# - 通过 C# 或 api 检测 VPN

c# - 为什么 var 只能在一条语句中声明和初始化?

java - 如何在 Java 中创建类型变量数组?

java - 使用泛型避免编译错误

javascript - 在reactJS中使用setState重新渲染时如何调用其他构造函数?

java - 自定义异常中的 super 调用

c# - 有没有办法动态确定启动时在 Azure webjob 中触发的队列数量和名称?

c# Directory.GetFiles 在驱动器 C 上给出 8.3 个文件名

c# - 关于泛型和继承(原谅我不好的标题)