H
Hans-Jürgen Philippi
Hi group,
let's say I have a 'Person' class with properties like 'FirstName',
'LastName', 'Birthday' and so on. Now I overload the 'Person' ToString()
method with an implementation ToString(string PlaceholderString) of the
following purpose:
When someone calls ToString("{LastName}, {FirstName}") on a given Person
instance, the expected result is e.g. "Doe, John" for this object, that is:
Any {property placeholder} is replaced by the actual instance value.
Furthermore, the ToString(string PlaceholderString) implementation is
intended to work with arbitrary properties on any class, without knowing the
members before.
I've achieved this with reflection: When ToString(string PlaceholderString)
is called, I loop over the type members to fetch the currently available
member/value pairs. In the same run, I do simple StringBuilder replacements
of requested {property placeholder} values within the user given
PlaceholderString and finally hand the replacement result out.
The whole thing works fine, I'm just asking myself: Is there a
better/faster/more efficient way to do this? Or did I reinvent the wheel and
there is an unknown .NET method with exactly the same function already?
Any hint is greatly appreciated.
Best regards,
Hans
let's say I have a 'Person' class with properties like 'FirstName',
'LastName', 'Birthday' and so on. Now I overload the 'Person' ToString()
method with an implementation ToString(string PlaceholderString) of the
following purpose:
When someone calls ToString("{LastName}, {FirstName}") on a given Person
instance, the expected result is e.g. "Doe, John" for this object, that is:
Any {property placeholder} is replaced by the actual instance value.
Furthermore, the ToString(string PlaceholderString) implementation is
intended to work with arbitrary properties on any class, without knowing the
members before.
I've achieved this with reflection: When ToString(string PlaceholderString)
is called, I loop over the type members to fetch the currently available
member/value pairs. In the same run, I do simple StringBuilder replacements
of requested {property placeholder} values within the user given
PlaceholderString and finally hand the replacement result out.
The whole thing works fine, I'm just asking myself: Is there a
better/faster/more efficient way to do this? Or did I reinvent the wheel and
there is an unknown .NET method with exactly the same function already?
Any hint is greatly appreciated.
Best regards,
Hans