【问题标题】:Construction of generic type parameter in HaxeHaxe中泛型类型参数的构造
【发布时间】:2015-06-03 02:32:01
【问题描述】:

我正在尝试基于函数类型参数实例化一个类。
虽然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

很明显,我做错了什么,但是什么?

【问题讨论】:

    标签: constructor haxe generic-type-argument


    【解决方案1】:

    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();
      }
    }
    

    【讨论】:

    • 这是否意味着我必须有一个 typedef 作为约束?
    • 一个 typedef 告诉编译器你将使用的构造函数的结构。
    • 我不明白为什么我需要这个 typedef... 一个类(恕我直言)应该足以告诉编译器什么是什么。无论如何,谢谢你。
    猜你喜欢
    • 1970-01-01
    • 2021-08-17
    • 2019-07-05
    • 1970-01-01
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多