【问题标题】:Associative Array where a class TypeInfo is key in D?关联数组,其中类 TypeInfo 是 D 中的关键?
【发布时间】:2010-07-01 22:02:04
【问题描述】:

我希望能够创建一个多维关联数组,其中一维是一个类。像这样:

class Node{
    Node[?classType?][string] inputs;
}

这样我以后可以做

Node[] getInputsOfType(?? aClass){
   if(aClass in this.inputs)
      return this.inputs[aClass];
   else
      return null;
}

// meanwhile in another file...

Node[] effects = someAudioNode.getInputsOfType(AudioEffect);

我只是迷路了。有什么想法吗?
关于最后一部分:一个类可以像这样单独用作参数吗? (本例中的AudioEffect 是一个类。)

BR

[更新/解决]

感谢您的回答!

我认为发布结果会很好。好的,我在源码中查了.classinfo,发现它返回了一个TypeInfo_Class的实例,并且有一个.name-property,一个string。所以这就是我想出的:

#!/usr/bin/env dmd -run
import  std.stdio;
class A{
    int id;
    static int newId;
    A[string][string] list;
    this(){ id = newId++; }
    void add(A a, string name){
        writefln("Adding: [%s][%s]", a.classinfo.name, name);
        list[a.classinfo.name][name] = a;
    }
    T[string] getAllOf(T)(){
        return cast(T[string]) list[T.classinfo.name];
    }
}
class B : A{ }
void main(){
    auto a = new A();
    a.add(new A(), "test");
    a.add(new B(), "bclass");
    a.add(new B(), "bclass2");

    auto myAList = a.getAllOf!(A);
    foreach(key, item; myAList)
        writefln("k: %s, i: %s id: %s",
                key, item.toString(), item.id);

    auto myBList = a.getAllOf!(B);
    foreach(key, item; myBList)
        writefln("k: %s, i: %s id: %s",
                key, item.toString(), item.id);
}

它输出:

Adding: [classtype.A][test]
Adding: [classtype.B][bclass]
Adding: [classtype.B][bclass2]
Trying to get [classtype.A]
k: test, i: classtype.A id: 1
Trying to get [classtype.B]
k: bclass2, i: classtype.B id: 3
k: bclass, i: classtype.B id: 2

所以是的,我想它有效。耶!有人有改进的想法吗?

这里有什么陷阱吗?

  • classinfo.name 会不会突然出现异常行为?
  • 是否有一种“正确”的方式来获取类名?

另外,这是最快的方法吗?我的意思是,所有类名似乎都以classtype. 开头。哦,那可能是另一个 SO-thread。再次感谢!

BR

【问题讨论】:

    标签: class d associative-array


    【解决方案1】:

    您可以使用ClassInfo 类(可通过.classinfo 属性访问)在运行时引用类类型。但是,ClassInfo 类没有实现在关联数组中使用的必要方法(请参阅D reference page on AAs 关于在 AA 中使用类/结构)。我想如果你为 ClassInfo 实现自己的包装器,可以用作 AA 密钥,这是可能的。这应该相当简单,因为您可以预期一个类类型将只有一个 ClassInfo 实例,因此您可以简单地使用 ClassInfo 的地址作为唯一哈希。


    顺便说一下,更简单更快捷的写法

    if (key in aa)
        return aa[key];
    else
        return null;
    

    auto pvalue = key in aa;
    return pvalue ? *pvalue : null;
    

    【讨论】:

    • 每个类只有一个类信息:如果您使用 DLL 或 SO,IIRC 可能不正确。但在这些情况下,您最终也会遇到其他问题。
    • 谢谢!我最终在 classinfo 中使用了.name-property,它只是一个字符串,所以在关联数组中使用没有问题,尽管感觉它可能更快。 /BR
    猜你喜欢
    • 2013-01-30
    • 2014-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    • 2015-06-11
    • 1970-01-01
    相关资源
    最近更新 更多