I have a class with lots of, lots of, lots of properties. In my programm i have to log heavily. Often I have to manually build log strings like
string log = "Current state of object:" + "Property1" + myObj.Property1 + ...
- 开发者_如何转开发
- I just thought what if override
ToString
and provide logging of whatever I need. It is considered goog practice? - How can I provide formatter control string? Say I want my ToString to operate in two modes one is complete ouput of all properties and another light version wheere only relevant properties are output
Something like MyObj.ToString("full") and MyObj.ToString("basic")
Overriding ToString
is indeed good practice, so long as you provide good information.
As for having different types of ToString
- this is possible, but then you will not be overriding ToString
, but providing an overload (that any using class will need to know about).
I would implement the lightweight
version as the override and create a VerboseToString
function for the full set of properties.
If you have many such objects, you can create a IVerboseString
interface with a VerboseToString
method and implement it in your objects. This way you can simply use the interface reference in your logging.
- That's an excellent practice
- You could, of course, parametrize the ToString method, but it would no longer mean an implicit conversion from object to string, so you can't write, say,
string x = myObject
; you will have to call ToString explicitly.
Why are you overriding ToString but not creating a method that takes Enum as parameter and does what you want inside?
I can't think of any particular problem associated with it, and myself I often appreciate it for spitting out info in unit tests or trace etc. but I'd take issue with your implementation for verbose and concise outputs - don't use voodoo strings or any kind of arbitrary input - I'd prefer it here id you either took an input argument bool verbose
or you explicitly created a ToStringVerbose()
method. It's also good practice IMHO for your overridden method to use base.ToString()
as part of it's implementation.
精彩评论