[유니티, C#] switch문의 파라미터로 Type 사용하기

2023. 5. 6. 14:29유니티, C#

클래스를 파라미터로 받아 switch문을 작성하고 싶었다.

 

[잘못된 방법1]

public void Func(Type type){
	switch(type)
	{
	  case Weapon weapon:
	    //...
	    break;
	  case Armor armor:
	    //...
	    break;
	}
}

[잘못된 방법2]

public void Func(Type type){
	switch(type)
	{
	  case typeof(Weapon):
	    //...
	    break;
	  case typeof(Armor):
	    //...
	    break;
	}
}

C#에서는 switch문의 파라미터에 클래스(Type type)를 넣는것이 가능하지만 위와 같은 경우에는 case 내의 조건이 실제 인스턴스로부터 받아온 type이 아닌 추정이기 때문에 안된다더라(정확히 이해 못했다).

https://stackoverflow.com/questions/43080505/how-to-switch-on-system-type

(Stack-Overflow 참조)

 


 

[해결한 방법1]

public void Func(Type type){
	switch (true)
	{
	    case true when typeof(Weapon).IsAssignableFrom(type):
        	//...
        	break;
	    case true when typeof(Armor).IsAssignableFrom(type):
        	//...
        	break;
	    case true when typeof(Weapon).IsAssignableFrom(type):
        	//...
        	break;
	    default:
        	break;
	}
}

그래서 IsAssignableFrom() 함수를 사용해 this, 즉 typeof(anything)이 type과 같으면 true를 리턴해 case문을 실행시키는 방식으로 작동되도록 했다.

 

[해결한 방법2]

public void Func(Type type){
	switch (type.Name)
	{
	    case nameof(Weapon):
        	//...
        	break;
	    case nameof(Armor)
        	//...
        	break;
	    case nameof(UsedItem)
        	//...
        	break;
	    default:
        	break;
	}
}

+ 이렇게 쉬운 방법이 있더라...

   이름으로 비교.. 확인 !