C# で をにキャストするint
にはどうすればよいですか?enum
ベストアンサー1
int から:
YourEnum foo = (YourEnum)yourInt;
文字列から:
YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);
// The foo.ToString().Contains(",") check is necessary for
// enumerations marked with a [Flags] attribute.
if (!Enum.IsDefined(typeof(YourEnum), foo) && !foo.ToString().Contains(","))
{
throw new InvalidOperationException(
$"{yourString} is not an underlying value of the YourEnum enumeration."
);
}
動的(コンパイル時に型が不明):
Type enumType = ...;
// NB: Enums can specify a base type other than 'int'
int numericValue = ...;
object boxedEnumValue = Enum.ToObject(enumType, numericValue);