开发者

Trying to get an int value from a String with Enum::Parse

开发者 https://www.devze.com 2023-03-07 01:48 出处:网络
I am working with C++ and .NET 1.1, and need to parse String values into their corresponding int values from an enumerator.

I am working with C++ and .NET 1.1, and need to parse String values into their corresponding int values from an enumerator.

I have an enumerator

__value static enum myEnum {
  VALU开发者_如何学GoE1,
  VALUE2,
  VALUE3
};

and I am trying to do something along the lines of

int value = (int)Enum::Parse(__typeof(myEnum), stringToParse);

or

int value = (myEnum)Enum::Parse(__typeof(myEnum), stringToParse);

except of course that Enum::Parse returns an Object*, and I just can't work out how to cast that object into an int.

What am I doing wrong? (Something to do with managed extensions, like last time I got stuck?)


It should just be an unbox - although you might want to unbox to the enum and then cast. In C#, something like;

int value = (int)(myEnum)Enum.Parse(typeof(myEnum), stringToParse);

Not sure what that looks like in C++ though.

In C# the following also works, but I can't guarantee how formally:

int value = (int)Enum.Parse(typeof(myEnum), stringToParse);

Note in the above I'm assuming that myEnum is using Int32 as the underlying type. If that is not the case, then you need tweak it to unbox as the correct underlying type first.

Running it through reflector, I get:

 Int32 __gc* value = *static_cast<__box Int32*>(
   *static_cast<__box myEnum*>(Enum::Parse(__typeof(myEnum), stringToParse)));
0

精彩评论

暂无评论...
验证码 换一张
取 消