C # extension method imaginative advanced Article Five: ToString (string format) extension

Source: Internet
Author: User
Tags datetime reflection regular expression string format tostring

In. NET, System.Object.ToString () is one of the most used methods, and the ToString () method is defined in the Object class as the Virtual,object class gives it a default implementation:

1 public virtual string ToString()
2 {
3  return this.GetType().ToString();
4 }

. NET native class or struct, such as int,datetime, to which it is rewritten (override), so that it returns a more valuable value than the name of the type. The reasonable rewriting of the ToString () method in programming, debugging in the great convenience. But after all, a class has only one ToString () method that does not meet our diverse needs, and many classes are overloaded with ToString (). As follows:

1 string dateString = DateTime.Now.ToString("yyyy");  //2009
2 string intString = 10.ToString("d4");  //0010

int, DateTime implements the ToString (string format) method, which greatly facilitates our use.

For our own defined types, we should also provide a reasonable ToString () rewrite, if we can provide another ToString (string format), it will make our later work simpler. Try the following types:

1 public class People
2 {
3  private List<People> friends = new List<People>();
4 
5  public int Id { get; set; }
6  public string Name { get; set; }
7  public DateTime Brithday { get; set; }
8  public People Son { get; set; }
9  public People[] Friends { get { return friends.ToArray(); } }
10
11  public void AddFriend(People newFriend)
12  {
13   if (friends.Contains(newFriend)) throw new ArgumentNullException("newFriend", "该朋友已添加");
14   else friends.Add(newFriend);
15  }
16  public override string ToString()
17  {
18   return string.Format("Id: {0}, Name: {1}", Id, Name);
19  }
20 
21 }

A simple class, we give a ToString () rewrite that returns a string containing the ID and name two key attributes. Now we need a ToString (string format) rewrite to meet the following applications:

1 People p = new People { Id = 1, Name = "鹤冲天", Brithday = new DateTime(1990, 9, 9) };
2 string s0 = p.ToString("Name 生日是 Brithday"); //理想输出:鹤冲天 生日是 1990-9-9
3 string s1 = p.ToString("编号为:Id,姓名:Name"); //理想输出:编号为:1,姓名:鹤冲天

Think about how to achieve it, and remember that format is variable, what attributes are not used, and what kind of combination ...

Perhaps a class is good to do, if we define a lot of classes, dozens of, hundreds of how to do? One by one implementing ToString (string format) would have worn people out. The good news is that we have an extension method, and we have an extended ToString (string format) for object. NET object is all the base class, and all classes are automatically owned when it is extended. Of course, the existing ToString (string format) is not implemented because the native method has a high priority and is not overwritten by the extension method.

To see how to achieve it (we will improve the step-by-step, in order to distinguish between the various versions, respectively, extended to ToString1, ToString2 ...) Corresponding version one, version two ... ):

1 public static string ToString1(this object obj, string format)
2 {
3   Type type = obj.GetType();
4   PropertyInfo[] properties =  type.GetProperties(
5   BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance);
6
7   string[] names = properties.Select(p => p.Name).ToArray();
8   string pattern = string.Join("|", names);
9
10   MatchEvaluator evaluator = match =>
11   {
12    PropertyInfo property = properties.First(p => p.Name == match.Value);
13    object propertyValue = property.GetValue(obj, null);
14    if (propertyValue != null) return propertyValue.ToString();
15    else return "";
16   };
17   return Regex.Replace(format, pattern, evaluator);
18 }

The 3~5 row obtains the public, instance's Get property (if it needs to be static or private, modifies line 5th) by reflection, and the 7~8 row dynamically generates a regular expression to match the Format,10~16 row as a successful match. Here is a reflection and regular expression, if not familiar, first debug run it, test the previous mentioned application:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.