C# 정확한 Type 의 비교 ( IsAssignableFrom vs is )

Unity3D/Problems 2016. 6. 9. 16:16
반응형

 var iWorldEquipment = this.controller.GetWorldInterfaceByType(typeof(IWorldEquipment)) as IWorldEquipment;



   public IWorld GetWorldInterfaceByType(System.Type worldInterfaceType)   //IWorldEquipment

    {

        Debug.LogFormat("<color=yellow>{0}</color>", worldInterfaceType);


        var enumerator = this.worldIterator.GetEnumerator();


        var a = worldInterfaceType is IWorldEquipment;


        Debug.Log(a);


        var b = worldInterfaceType.GetType().Equals(typeof(IWorldEquipment));


        Debug.Log(b);


        var c = worldInterfaceType.IsAssignableFrom(typeof(IWorldEquipment));


        Debug.Log(c);


        var d = worldInterfaceType.Equals(typeof(IWorldEquipment));


        Debug.Log(d);


        return null;

    }



C# 정확한 Type 의 비교 ( IsAssignableFrom vs is )


int a;

(a is int)


이런 간단한 타입 비교는 is 가 쉽고 간편하다.




다만 단순 비교로는 타입체크하기 힘든 경우들이 있다.


예를들어 Generic 을 사용 한 타입들, ex) List<T>, Dictionary<T,K> 등등

또는 다차원 배열들 ex) int[3,5] 등등


이런 경우 사용하는 IsAssignableFrom 라는 함수 가 있다. 사용법은 아래와 같다.


private void DoSomethingWithFields<T>(T obj)
{
    // Go through all fields of the type.
    foreach (var field in typeof(T).GetFields())
    {
        var fieldValue = field.GetValue(obj);

        // You would probably need to do a null check
        // somewhere to avoid a NullReferenceException.

        // Check if this is a list/array
        if (typeof(IList).IsAssignableFrom(field.FieldType))
        {
            // By now, we know that this is assignable from IList, so we can safely cast it.
            foreach (var item in fieldValue as IList)
            {
                // Do you want to know the item type?
                var itemType = item.GetType();

                // Do what you want with the items.
            }
        }
        else
        {
            // This is not a list, do something with value
        }
    }
}





아래는 MSDN 에 나와있는 예제이다.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
using System;
using System.Collections.Generic;
class Program
{
    public static void Main()
    {
            // Demonstrate classes:
            Console.WriteLine("Defned Classes:");
            Room room1 = new Room();
            Kitchen kitchen1 = new Kitchen();
            Bedroom bedroom1 = new Bedroom();
            Guestroom guestroom1 = new Guestroom();
            MasterBedroom masterbedroom1 = new MasterBedroom();

            Type room1Type = room1.GetType();
            Type kitchen1Type = kitchen1.GetType();
            Type bedroom1Type = bedroom1.GetType();
            Type guestroom1Type = guestroom1.GetType();
            Type masterbedroom1Type = masterbedroom1.GetType();

            Console.WriteLine("room assignable from kitchen: {0}", room1Type.IsAssignableFrom(kitchen1Type));
            Console.WriteLine("bedroom assignable from guestroom: {0}", bedroom1Type.IsAssignableFrom(guestroom1Type));
            Console.WriteLine("kitchen assignable from masterbedroom: {0}", kitchen1Type.IsAssignableFrom(masterbedroom1Type));

            // Demonstrate arrays:
            Console.WriteLine();
            Console.WriteLine("Integer arrays:");

            int[] array2 = new int[2];
            int[] array10 = new int[10];
            int[,] array22 = new int[2, 2];
            int[,] array24 = new int[2, 4];

            Type array2Type = array2.GetType();
            Type array10Type = array10.GetType();
            Type array22Type = array22.GetType();
            Type array24Type = array24.GetType();

            Console.WriteLine("int[2] assignable from int[10]: {0}", array2Type.IsAssignableFrom(array10Type));
            Console.WriteLine("int[2] assignable from int[2,4]: {0}", array2Type.IsAssignableFrom(array24Type));
            Console.WriteLine("int[2,4] assignable from int[2,2]: {0}", array24Type.IsAssignableFrom(array22Type));

            // Demonstrate generics:
            Console.WriteLine();
            Console.WriteLine("Generics:");

            // Note that "int?[]" is the same as "Nullable<int>[]" 
            int?[] arrayNull = new int?[10];
            List<int> genIntList = new List<int>();
            List<Type> genTList = new List<Type>();

            Type arrayNullType = arrayNull.GetType();
            Type genIntListType = genIntList.GetType();
            Type genTListType = genTList.GetType();

            Console.WriteLine("int[10] assignable from int?[10]: {0}", array10Type.IsAssignableFrom(arrayNullType));
            Console.WriteLine("List<int> assignable from List<Type>: {0}", genIntListType.IsAssignableFrom(genTListType));
            Console.WriteLine("List<Type> assignable from List<int>: {0}", genTListType.IsAssignableFrom(genIntListType));

            Console.ReadLine();

    }
}
class Room
{
}

class Kitchen : Room
{
}

class Bedroom : Room
{
}

class Guestroom : Bedroom
{
}

class MasterBedroom : Bedroom
{
}

//This code example produces the following output: 
// 
// Defned Classes: 
// room assignable from kitchen: True 
// bedroom assignable from guestroom: True 
// kitchen assignable from masterbedroom: False 
// 
// Integer arrays: 
// int[2] assignable from int[10]: True 
// int[2] assignable from int[2,4]: False 
// int[2,4] assignable from int[2,2]: True 
// 
// Generics: 
// int[10] assignable from int?[10]: False 
// List<int> assignable from List<Type>: False 
// List<Type> assignable from List<int>: False


반응형

'Unity3D > Problems' 카테고리의 다른 글

NavMeshAgent 목표포착  (0) 2016.06.09
EditorGUILayout.ObjectField obsolete?  (0) 2016.06.09
LitJSON Limitations/Warnings  (0) 2016.05.10
페이스북 sdk 컴파일 오류 7.5  (0) 2016.05.01
Google.JarResolver.ResolutionException  (0) 2016.04.05
: