欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Unity 如何判断一个c#对象是否为List ?

程序员文章站 2022-03-04 12:37:03
...
if (obj.GetType().IsGenericType && obj.GetType().GetGenericTypeDefinition() == typeof(List<>)) {                        
}

通过这种方法,我们就写出了debug输出list和dictionary的功能

public static void Log(string key, params object[] args){
    string str;
    if (args.Length > 0) {
        str = key + " : ";
        foreach (object obj in args) {
            if (obj.GetType ().IsGenericType) {
                var type = obj.GetType ().GetGenericTypeDefinition ();
                if (type == typeof(List<>)) {
                    for (int i = 0; i < ((IList)obj).Count; i++) {
                        str += ((IList)obj)[i].ToString() + ",";
                    }
                    continue;
                }else if(type == typeof(Dictionary<,>)) {
                    foreach (DictionaryEntry unit in ((IDictionary)obj)) {
                        str+= unit.Key +":" + unit.Value+",";
                    }
                    continue;
                }
            }
            str += obj.ToString () + ",";
        }
    } else {
        str = "ZSDebug : " + key;
    }
    Debug.Log (str);
}

拿去用吧 :P