只需在Visual Studio for C ++中创建CLR控制台应用程序并复制此代码:
#include "stdafx.h"
using namespace System;
generic <typename TEnumMgd>
where TEnumMgd : value class, System::ValueType, System::IConvertible
public ref class EnumerationGenericClass
{
public:
EnumerationGenericClass(TEnumMgd value)
{
String^ text = value.ToString(); // Cannot compile
}
};
public enum class Test{ Foo, Bar };
int main(array<System::String ^> ^args)
{
auto obj = gcnew EnumerationGenericClass<Test>(Test::Foo);
return 0;
}
这失败了&#34;错误C2228:&#39; .ToString&#39;必须有class / struct / union&#34;,但为什么以及如何解决这个问题呢?最好没有任何拳击。
更新:更改格式以分开问答。
答案 0 :(得分:1)
如果您改为编写,则可以编译:
String^ text = value->ToString();
也就是说,C ++ / CLI使用&#34; - &gt;&#34;无论什么,通用类型的访问器。但是,为ctor输出的IL如下所示,因此它不是盒装的,而是被约束为预期的值类型。
.method public hidebysig specialname rtspecialname
instance void .ctor(!TEnumMgd 'value') cil managed
{
// Code size 29 (0x1d)
.maxstack 1
.locals ([0] string text)
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldarg.0
IL_0003: call instance void [mscorlib]System.Object::.ctor()
IL_0008: ldarga.s 'value'
IL_000a: constrained. !TEnumMgd
IL_0010: callvirt instance string [mscorlib]System.ValueType::ToString()
IL_0015: stloc.0
IL_0016: ldloc.0
IL_0017: call void [mscorlib]System.Console::WriteLine(string)
IL_001c: ret
} // end of method EnumerationGenericClass`1::.ctor