Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 根据类型重载泛型类的构造函数_C#_Generics_Constructor - Fatal编程技术网

C# 根据类型重载泛型类的构造函数

C# 根据类型重载泛型类的构造函数,c#,generics,constructor,C#,Generics,Constructor,除了默认构造函数之外,我正在尝试重载一个构造函数,它只会被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类型调用

如果不可能,为什么

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
    }
}
类程序
{
静态void Main()
{
//调用默认construcotr
var-OGenerics_string=新泛型();
//如何为int类型创建不同的构造函数
var-OGenerics_int=新泛型();
}
类泛型
{
公共仿制药()
{
}
//创建一个仅对int调用的构造函数
}
}

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

类泛型
{
公共仿制药()
{
}
公共静态泛型CreateIntVersion()
{
///在这里创建泛型
}
}

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

您可以找到传递的类型,以及它的int-do逻辑

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
}
void Main()
{
新的泛型();
新的泛型();
}
类泛型
{
公共仿制药()
{
如果(typeof(T)=typeof(int))InitForInt();
}
私有void InitForInt()
{
Console.WriteLine(“Int!”);
}
//创建一个仅对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
}