- First we have 2 classes, which overrides the ToString() method and use the Format method as defined as an extension method.
- The ToString() method from class Person, will invoke the property DrivingLicenses which will trigger the ToString() method of the class License.
- This example shows how the method Format(), format List<T>.
You can see my screencast.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using DynamicSugarSharp; namespace ScreenCastConsole { public class License { public DateTime Date; public string Type; public override string ToString() { return this.Format("Type:{Type} - Date :{Date:yyyy-MM-dd}"); } } public class Person { public string LastName { get; set; } public string FirstName { get; set; } public DateTime BirthDate { get; set; } public List<License> DrivingLicenses = null; public override string ToString() { var format = @" Name :{LastName}, {FirstName} BirthDate :{BirthDate:yyyy-MM-dd} DrivingLicenses :{DrivingLicenses} "; return this.Format(format); } } public static class ExtensionMethods { public static string Format(this Person person, string format, params object[] args) { return ExtendedFormat.Format(person, format, args); } public static string Format(this License person, string format, params object[] args) { return ExtendedFormat.Format(person, format, args); } } class Program { static void Main(string [] args) { var p = new Person(){ LastName = "TORRES", FirstName = "Frederic", BirthDate = new DateTime(1964, 12, 11), DrivingLicenses = DS.List( new License() { Date = new DateTime(1983, 1, 2), Type = "Cars" }, new License() { Date = new DateTime(1985, 4, 5), Type = "MotoBike" } ) }; Console.WriteLine(p.ToString()); Console.WriteLine("Hit enter to end the application"); Console.ReadLine(); } } }
Here is this output
Name :TORRES, Frederic
BirthDate :1964-12-11
DrivingLicenses :[Type:Cars - Date :1983-01-02, Type:MotoBike - Date :1985-04-05]
Hit enter to end the application
No comments:
Post a Comment