C#打印日志的小技巧(转)

https://www.cnblogs.com/jqg-aliang/p/5234206.html

打印日志的函数
开发中输出日志必不可少,在C#中输出多个不同类型参数的时候,需要连接符累加输出,很是不方便。
一个简单的方法是自己封装一个打印的函数,让它支持不定参数和不同类型的输出。这样就不会强用字符串进行拼接输出了。

public void Log(params Object[] message)
{
    string str = string.Empty;
    if (message == null || message.Length == 0)
    {
        str = "null";
    }
    else
    {
        for (int i = 0; i < message.Length; i++)
        {
            if (str.Length > 0)
            {
                str += " ";
            }
            str += message[i];
        }
    }
    Console.WriteLine(str); 
    // 写入到log日志文件
    StreamWriter sw = new StreamWriter(@"test.log", true, Encoding.UTF8);
    sw.WriteLine(str);
    sw.Close();
}

OK,现在看看这个函数的使用:假如这个类叫Unitl,需要打印的时候直接Util.Log("hello world");
貌似没有多大的区别,但是还可以这么玩:Util.Log(1,4,0.5,-1); 、 Util.Log(“test”,true,56);
OK,小技巧而已,没什么高大上的技术。使用了params 接收不定参数,而Object接收任意类型,这样一个简易封装的输出函数搞定。

原文地址:https://www.cnblogs.com/wsq-blog/p/10661402.html