How can I cast int to enum?

后端 未结 30 1516
礼貌的吻别
礼貌的吻别 2020-11-22 00:56

How can an int be cast to an enum in C#?

30条回答
  •  心在旅途
    2020-11-22 01:04

    You just do like below:

    int intToCast = 1;
    TargetEnum f = (TargetEnum) intToCast ;
    

    To make sure that you only cast the right values ​​and that you can throw an exception otherwise:

    int intToCast = 1;
    if (Enum.IsDefined(typeof(TargetEnum), intToCast ))
    {
        TargetEnum target = (TargetEnum)intToCast ;
    }
    else
    {
       // Throw your exception.
    }
    

    Note that using IsDefined is costly and even more than just casting, so it depends on your implementation to decide to use it or not.

提交回复
热议问题