Re: Formatted object properties with ToString() method
- From: "Hans-Jürgen Philippi" <HJPhilippi@xxxxxxx>
- Date: Tue, 10 Jun 2008 11:04:27 +0200
Hi Göran,
the way you use a regular expression to derive a format string is nice. But
doing it like this, you need to know the class properties at design time and
have to maintain a lookup array as well as a custom fitting String.Format()
method by hand - where I wanted an approach to have ToString(string
PlaceholderString) generally working even in derived classes with completely
new, unforeseen members!
Maybe I mix my implementation with your code to create the props and
String.Format() args arrays dynamically via reflection and benefit from the
cool Regex appeal. ;-)
Well, it appears like reflection is the tradeoff for the flexibility I need
and there will hardly be a much more efficient (=faster, reliable, easy on
resources *and* easy to maintain) way to do this.
Thanks for your input,
Hans
"Göran Andersson" <guffa@xxxxxxxxx>:
How about this:
string[] props = new string[] { "FirstName", "LastName", "Birthday" };
string format = Regex.Replace(PlaceHolderString, @"\{(\w+)\}",
delegate(Match m) { for (int i = 0; i < props.Length; i++) if
(m.Groups[1].Value == props[i]) return "{" + i.ToString() + "}"; return
m.Value; });
return string.Format(format, FirstName, LastName, Birthday);
Just add the names of the properties in the array and in the Format call.
.
- Follow-Ups:
- Re: Formatted object properties with ToString() method
- From: Marc Gravell
- Re: Formatted object properties with ToString() method
- References:
- Formatted object properties with ToString() method
- From: Hans-Jürgen Philippi
- Re: Formatted object properties with ToString() method
- From: Göran Andersson
- Formatted object properties with ToString() method
- Prev by Date: Re: Help adding service reference
- Next by Date: Re: Binding to INotifyCollectionChanged event
- Previous by thread: Re: Formatted object properties with ToString() method
- Next by thread: Re: Formatted object properties with ToString() method
- Index(es):
Relevant Pages
|