基于类型重载通用类的构造函数

4

我试图为除默认构造函数之外的类型int重载一个构造函数。 我找到的最接近的方法是 这个

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

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
    }
}

1
你实际上不能这样做,而且这也是一种代码异味。 - DavidG
2个回答

8

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

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

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

除此之外,你需要使用反射检查共享构造函数中的通用类型并分支代码,这样会相当丑陋。


4
你可以查找传递的类型,如果是int类型,则执行一些逻辑。
void Main()
{
    new Generics<string>();
    new Generics<int>();
}

class Generics<T>
{
    public Generics()
    {
        if(typeof(T) == typeof(int)) InitForInt();
    }

    private void InitForInt()
    {
        Console.WriteLine("Int!");      
    }
    // create a constructor which will get called only for int
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接