我正在尝试重载默认构造函数之外的构造函数,该构造函数只会被调用为 int 类型。我得到的最接近的东西是 this

如果不可能,那是为什么?

class Program
{
    static void Main()
    {
        //default construcotr get called
        var OGenerics_string = new Generics<string>();

        //how to make a different construcotr for type int
        var OGenerics_int = new Generics<int>();
    }

    class Generics<T>
    {
        public Generics()
        {
        }
        // create a constructor which will get called only for int
    }
}

最佳答案

不可能基于泛型类型重载构造函数(或任何方法) - 但您可以创建一个工厂方法:

class Generics<T>
{
    public Generics()
    {
    }

    public static Generics<int> CreateIntVersion()
    {
          /// create a Generics<int> here
    }
}

除此之外,您必须使用反射检查共享构造函数中的泛型类型并对代码进行分支,这将非常难看。

关于c# - 基于类型重载泛型类的构造函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45864383/

10-11 01:51