除了默认构造函数之外,我正在尝试重载一个构造函数,它只会在类型为 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/