Haxe中泛型类型参数的构造

Construction of generic type parameter in Haxe

我正在尝试根据函数类型参数实例化 class。
虽然 documentation 说可以,但我做不到。

考虑以下代码:

// Dialog base class
// Every dialog in my application will derive from this
class Dialog
{
    public function new()
    {
        // do some stuff here
    }
}

// One of the possible dialogs in the application
// Extends Dialog
class TestDialog extends Dialog
{
    public function new()
    {
        super();
        // do some more stuff
    }
}

// A simple class that tries to instantiate a specialized dialog, like TestDialog 
class SomeAppClass
{
    public function new() 
    {
        var instance = create(TestDialog);
    }

    @:generic
    function create<T:Dialog>(type:Class<T>):T
    {
        return new T();
    }
}

这不适用于以下错误:
create.T does not have a constructor

显然,我做错了什么,但是什么?

SpecialDialog 构造函数 可能与 Dialog 不同。 所以你必须 约束它 然后也约束 Dialog.

Code @ Try Haxe

package;


typedef Constructible = {
  public function new():Void;
}


// Dialog base class
// Every dialog in my application will derive from this
class Dialog
{
    public function new()
    {
        trace("dialog");
    }
}


class SuperDialog extends Dialog
{
    public function new()
    {
        super();
        trace("super dialog");
    }
}

// A simple class that tries to instantiate a specialized dialog, like TestDialog 

class SomeAppClass
{
    public function new() 
    {
        var dialog = create(Dialog);
        var superDialog = create(SuperDialog);
    }

    @:generic
    public static function create<T:(Constructible,Dialog)>(type:Class<T>):T
    {
        return new T();
    }
}

class Test {
  static public function main() {
    new SomeAppClass();
  }
}