如何通过Mono API静态获取MonoClassField的实际泛型参数?
静态获取Mono字段的泛型参数(含Nullable场景)
你的现有代码能处理普通泛型类,但针对System.Nullable<T>(如bool?),需要单独判断并直接取其泛型参数作为底层类型,以下是无需依赖实例的静态实现方案:
MonoType* m_type = mono_field_get_type(_field); MonoType* underlying_type = NULL; // 先判断当前类型是否为泛型实例 if (m_type->type == MONO_TYPE_GENERICINST) { MonoClass* type_class = mono_class_from_mono_type(m_type); MonoGenericContainer* generic_container = mono_class_try_get_generic_container(type_class); // 获取System.Nullable`1的定义类 MonoClass* nullable_class = mono_class_get(mono_defaults.corlib, "System", "Nullable`1"); if (generic_container && generic_container->klass == nullable_class) { // Nullable<T>的泛型参数就是底层值类型 MonoGenericInst* nullable_inst = mono_type_get_generic_inst(m_type); underlying_type = nullable_inst->type_argv[0]; } else { // 处理普通泛型类的原有逻辑 MonoGenericInst* generic_inst = generic_container->context.class_inst; underlying_type = generic_inst->type_argv[generic_args_offset]; } } else { // 非泛型类型直接使用原类型 underlying_type = m_type; }
核心说明:
- 精准场景区分:通过
MONO_TYPE_GENERICINST标记识别泛型实例类型,再对比泛型容器的类是否为System.Nullable的定义类,避免和普通泛型类混淆 - 正确获取泛型实例:对Nullable类型,直接用
mono_type_get_generic_inst从MonoType获取泛型实例,比从MonoClass上下文取值更准确 - 纯静态元数据操作:所有逻辑仅依赖类型定义、类元数据完成,完全不需要创建或依赖对象实例
内容的提问来源于stack exchange,提问作者Lucifer Morningstar
相关产品推荐
相关产品推荐

