180bpm

Safe use of the increment and decrement operator in enum 본문

Develop/C#

Safe use of the increment and decrement operator in enum

powdersnow 2019. 12. 17. 18:19
/*
enum enum
{
a=0, b=1,
};
*/
enum val = enum.a;
val++;
Debug.Log(val); // a
Debug.Log(System.Enum.IsDefined(typeof(enum), val)); // True
val++;
Debug.Log(val);							// 2
Debug.Log((enum)val);					// 2
Debug.Log(System.Enum.IsDefined(typeof(enum), val)); // False
yield break;

C#이 웃긴게 enum에 증감연산자가 무한정 들어간다.

그리고 가끔 값도 이상한거 뱉을때도 있고..캐스팅할때 선언이 안되어있더라도 캐스팅이 된다.

그래서 증감연산자 필요할때 안전하게 처리하려면 System.Enum.IsDefined로 체크.

Comments