开发者

Simplest way to make generic logging in C#

I am new to C#, but still

public class Logging
{ 
    public static int Write(params object[] items)
    {
        return Console.Write(i开发者_JAVA技巧tems);
    }
}

seems just ok, but does not work. Well it is not obvious that all instances or Write are defined in compile time, but they are.

If i call

Logging.Write("Hello world");

i got string

System.Object[]

as response


There are two problems with your code:

  1. There is no overload of the Console.Write method that does not return void (e.g., int).

  2. There is no overload of the Console.Write method that takes an array of object. The overload matching is the one taking a single object which converts the object to string by invoking the ToString method. The ToString method returns "System.Object[]" for an array of object.


Are you trying to do something like this?

public class Logging
{ 
    public static void Write(params object[] items)
    {
        Console.WriteLine(string.Join(" ", items));
    }
}

Example:

int x = 42;
Logging.Write("The value of x is", x);

Output:

The value of x is 42


i know this is not what your question is about, but i would suggest using a logging library, i love NLog, then there is Log4Net there are more but those are those i know about!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜