如何在C ++ / CLI中将非可空类型转换为可空?
我知道如何在C#中执行此操作:
public Type GetNullableType(Type t)
{
return typeof(Nullable<>).MakeGenericType(t);
}
但我无法弄清楚,如何将其转换为C ++ / CLI。
我试过这个,但是当我编译代码时,我得到了内部编译器错误。
Type^ nullableType = Nullable<>.GetType();
return nullableType->MakeGenericType(t);
答案 0 :(得分:2)
另一个不那么脆弱的解决方法:
static Type^ GetNullableType(Type^ t)
{
Type^ nullable = Nullable<int>::typeid->GetGenericTypeDefinition();
return nullable->MakeGenericType(t);
}
答案 1 :(得分:1)
首先,在C ++中使用typeof()
而不是C#typeid
。因此,typeof(int)
变为int::typeid
。
其次,在引用泛型类型时,您似乎只省略了尖括号。因此,typeof(List<>)
变为List::typeid
。
这个问题是你不能指定类型参数的数量。 Nullable::typeid
返回非泛型静态类Nullable
的类型,这不是我们想要的。
我没有找到直接从C ++ / CLI获取类型的方法。但您始终可以使用Type.GetType()
:
Type^ nullableType = Type::GetType("System.Nullable`1");
return nullableType->MakeGenericType(t);
(`1
是.Net内部用来区分具有不同类型参数的类型的方式。)
如果Nullable<T>
类型被移出mscorlib,这将停止工作,但我怀疑会发生这种情况。