2011-11-17 92 views
2

如何在C++/CLI中将非空类型转换为可空?如何在C++/CLI中将非空类型转换为可空?

我知道该怎么做,在C#:

public Type GetNullableType(Type t) 
{ 
    return typeof(Nullable<>).MakeGenericType(t); 
} 

但我无法弄清楚,如何将其转换为C++/CLI。

我试过这个,但是当我编译代码时,我得到了内部编译器错误。

Type^ nullableType = Nullable<>.GetType(); 
return nullableType->MakeGenericType(t); 

回答

2

另一个不那么脆解决方法:

static Type^ GetNullableType(Type^ t) 
{ 
    Type^ nullable = Nullable<int>::typeid->GetGenericTypeDefinition(); 
    return nullable->MakeGenericType(t); 
} 
0

第一,而不是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 IS .NET内部使用与类型参数不同的计数来区分类型的方式。)

这将停止工作,如果Nullable<T>类型是不断移动出于mscorlib,但我怀疑会发生。

+0

谢谢您的回答。可以写: 'Type^nullableType = Type :: GetType(“System.Nullable'1”);' – FeatureShock

+0

你是对的。这也应该工作,我会更新我的答案。 – svick

相关问题