数组、列表和字典等可枚举类型的控制台输出扩展方法

需求

        在程序开发中我们经常需要对数组、列表和字典等可枚举类型进行调试输出,每次都去手动敲一个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来源。主要是提供了一种思路,读者可根据具体需求自行修改,值得注意的是,这些控制台输出的方法不应构建到发行版中,所以需要注意代码过滤。

如果这篇文章对你有帮助,请给作者点个赞吧! 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值