我正在尝试重载除默认构造函数之外的构造函数,只会调用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
}
}
答案 0 :(得分:7)
根据泛型类型重载构造函数(或任何方法)是不可能的 - 但您可以创建工厂方法:
class AncestorClass {
constructor (name, id){
this.name = name + id;
}
logName () {
console.log(this.name);
}
}
class ParentClass extends AncestorClass {
constructor (name, id) {
super(name, 1);
this.name = name + id;
}
}
class ChildClass extends ParentClass {
constructor (name, id) {
super(name, 2);
this.name = name + id;
}
}
class GrandchildClass extends ChildClass {
constructor (name, id){
super(name, 3);
this.name = name + id;
}
}
const grandchild = new GrandchildClass('testName', 4);
const parent = Object.getPrototypeOf((Object.getPrototypeOf(grandchild.constructor)));
console.log(parent);
const initParent = new parent('foo', 1);
initParent.logName();
除此之外,您必须使用反射检查共享构造函数中的泛型类型并对代码进行分支,这将非常难看。
答案 1 :(得分: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
}