【问题标题】:How can I keep the Generics type in the C# code output from Haxe?如何在 Haxe 的 C# 代码输出中保留泛型类型?
【发布时间】:2020-04-05 06:32:00
【问题描述】:

我想在 C# 中使用类型为数组。

我尝试在 Haxe 4.0.5 中构建以下代码,但 hoges 在 C# 中是 Array<object>。 (我想要Array<Hoge>

class ArrayTest
{
    public var hoges: Array<Hoge>;
}

class Hoge
{
    public var x: Int;
    public var y: Int;
    public var z: Int;
}

我在 github 上找到了以下帖子,并了解此行为是使代码更快的规范。 https://github.com/HaxeFoundation/haxe/issues/5434#issuecomment-230581990.

但是,我希望它带有一个类型,因为我想将此代码用作接口。 有什么解决方法吗?

【问题讨论】:

    标签: haxe


    【解决方案1】:

    如果主要是为了与外部代码交互,使用特定于 C# 的集合可能更合适:

    import cs.system.collections.generic.List_1;
    
    class Main {
        public static var hoges:List_1<Hoge> = new List_1();
        static function main() {
            hoges.Add(new Hoge());
            trace(hoges[0]);
        }
    }
    class Hoge {
        public var x: Int;
        public var y: Int;
        public var z: Int;
        public function new() {}
    }
    

    产生

    public static global::System.Collections.Generic.List<global::Hoge> hoges;
    

    如你所料。

    摘要可用于根据目标平台切换实现。

    【讨论】:

    • 感谢您的回复!我试图从相同的源代码生成 C# 和 javascript 代码。除了使用编译器标志进行控制之外,还有其他聪明的方法吗?
    • 您可以让#if cs/#if js/等根据目标平台选择实现——每个平台自动声明一个或多个编译器标志;使用库时,也可以使用#if
    【解决方案2】:

    你可以使用 NativeArray

    typedef Hoges = cs.NativeArray<Hoge>;
    class ArrayTest { public var hoges: Hoges; }
    

    生成

    public global::Hoge[] hoges;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多