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:
There is no overload of the Console.Write method that does not return
void
(e.g.,int
).There is no overload of the Console.Write method that takes an array of
object
. The overload matching is the one taking a singleobject
which converts theobject
tostring
by invoking the ToString method. The ToString method returns"System.Object[]"
for an array ofobject
.
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!
精彩评论