需求
在程序开发中我们经常需要对数组、列表和字典等可枚举类型进行调试输出,每次都去手动敲一个for或foreach循环比较麻烦,所以我们可以考虑用一个静态类为可枚举类型添加扩展方法,从而实现快速输出可枚举类型的数据。
代码(C#)
LogUtility.cs
#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace LogToolAPI
{
[System.Diagnostics.DebuggerStepThrough]
public static class LogUtility
{
public static void Log<T>(this IEnumerable<T> source, string prefix = "")
{
string str = source == null ? "Null" : string.Join(", ", source);
Debug.Log(prefix + str);
}
public static void Log<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selecter, string prefix = "")
{
string str = source == null ? "Null" : string.Join(", ", source.Select(selecter));
Debug.Log(prefix + str);
}
}
}
#endif
示例代码
List<int> v_list = new List<int> { 1, 2, 3, 4, 5 };
int[] v_array = new int[] { 1, 2, 3, 4, 5 };
Dictionary<int, string> v_dict = new Dictionary<int, string>();
for (int i = 0; i < 5; i++)
{
v_dict.Add(i, "Value:" + i.ToString());
}
v_array.Log("Array:");
v_list.Log("List:");
v_dict.Log(kv => kv.Value, "Dict:");
v_list = null;
v_array = null;
v_dict = null;
说明
代码中我们使用了C#扩展方法的机制为所有可枚举类型添加了两种Log方法,本篇文章是基于Unity3D的部分API,但是这不是必须的,而是取决于Debug.Log的API来源。主要是提供了一种思路,读者可根据具体需求自行修改,值得注意的是,这些控制台输出的方法不应构建到发行版中,所以需要注意代码过滤。
如果这篇文章对你有帮助,请给作者点个赞吧!