constructor - Haxe中泛型类型参数的构建

标签 constructor haxe generic-type-argument

我正在尝试根据函数类型参数实例化一个类。
虽然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();
  }
}

关于constructor - Haxe中泛型类型参数的构建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30609852/

相关文章:

spring - Mockito 注入(inject)不适用于构造函数和 setter 模拟

java - 将构造函数方法拆分为多个部分 - 最终值的问题

haxe - 非类型类型参数

haxe - 如何使用 Haxe "package"声明?

actionscript-3 - 如何在 Haxe 中正确重写 getter 和 setter

vb.net - 通用 TypeOf 运算符?

c# - 当一个构造函数实现另一个构造函数时有好处还是坏处?

c++ - 检测默认构造函数是否有效

c++ - 如何使用 C++ 在数组中存储不同的值类型?

java - 检查异常差异