问题描述
我是Vala的新手,并且玩了一下。目前我正在寻找一种在运行时确定泛型列表的类型参数的方法。下面的代码使用'反射'来打印Locations类的属性。但是,我无法在运行时确定此列表包含字符串实例。
有没有办法做到这一点?或者在Vala中不支持?
使用Gee;
类位置:对象{
public string numFound {get;组; }
public ArrayList< string> docs {get;组; }
}
void main(){
ObjectClass ocl =(ObjectClass)typeof(Locations).class_ref();
ParamSpec [] properties = ocl.list_properties();
foreach(属性中的ParamSpec spec){
string fieldName = spec.get_nick();
stdout.printf(fieldName:%s\,fieldName);
类型fieldType = spec.value_type;
stdout.printf(Type:%s\\\
,fieldType.name());
$ / code $ / pre
$ b $输出:
fieldName:numFound
类型:gchararray
fieldName:docs
类型:GeeArrayList
解决方案没有一种通用的方法可以做到这一点,因为GObject / GType根本不具有表现力。例如,如果您使用的是 GLib.GenericArray
(或者 GLib.List
)而不是 Gee.ArrayList
你会不走运。
也就是说,libgee确实提供了一种方法。像大多数libgee中的容器一样, Gee.ArrayList
implements ,其中包括属性。但是请注意,您需要一个实例,而不仅仅是 GLib.ObjectClass
。
I am new to Vala and playing around a bit. Currently I am looking for a way to determine the type parameter of a generic list at runtime.
The code below uses 'reflection' to print the properties of the Locations class. However, I am not able to determine at runtime that this list contains instances of string.
Is there a way to do this? Or is this not supported in Vala?
using Gee;
class Locations : Object {
public string numFound { get; set; }
public ArrayList<string> docs { get; set; }
}
void main () {
ObjectClass ocl = (ObjectClass) typeof (Locations).class_ref ();
ParamSpec[] properties = ocl.list_properties ();
foreach (ParamSpec spec in properties) {
string fieldName = spec.get_nick ();
stdout.printf (" fieldName: %s\n", fieldName);
Type fieldType = spec.value_type;
stdout.printf (" Type : %s\n", fieldType.name());
}
}
Output:
fieldName: numFound
Type : gchararray
fieldName: docs
Type : GeeArrayList
解决方案 There isn't a generic way to do this since GObject/GType simply isn't that expressive. For example, if you were using a GLib.GenericArray
(or a GLib.List
) instead of a Gee.ArrayList
you would be out of luck.
That said, libgee does provide a way. Like most containers in libgee, Gee.ArrayList
implements Gee.Traversable
, which includes the element_type
property. Note, however, that you need an instance, not just the GLib.ObjectClass
.
这篇关于Vala:在运行时确定List内的泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!