日期:2014-05-18  浏览次数:20825 次

C#扩展方法

扩展方法:ToString()

public static class ObjectUnits

? ? {

? ? ? ? public static string ToString(this object obj, string format)

? ? ? ? {

? ? ? ? ? ? Type type = obj.GetType();

? ? ? ? ? ? PropertyInfo[] properties = type.GetProperties(

? ? ? ? ? ? ? ? BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance);

?

? ? ? ? ? ? MatchEvaluator evaluator = match =>

? ? ? ? ? ? {

? ? ? ? ? ? ? ? string propertyName = match.Groups["Name"].Value;

? ? ? ? ? ? ? ? string propertyFormat = match.Groups["Format"].Value;

?

? ? ? ? ? ? ? ? PropertyInfo propertyInfo = properties.FirstOrDefault(p => p.Name == propertyName);

? ? ? ? ? ? ? ? if (propertyInfo != null)

? ? ? ? ? ? ? ? {

? ? ? ? ? ? ? ? ? ? object propertyValue = propertyInfo.GetValue(obj, null);

? ? ? ? ? ? ? ? ? ? if (string.IsNullOrEmpty(propertyFormat) == false)

? ? ? ? ? ? ? ? ? ? ? ? return string.Format("{0:" + propertyFormat + "}", propertyValue);

? ? ? ? ? ? ? ? ? ? else return propertyValue.ToString();

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? else return match.Value;

? ? ? ? ? ? };

? ? ? ? ? ? string pattern = @"\[(?<Name>[^\[\]:]+)(\s*:\s*(?<Format>[^\[\]:]+))?\]";

? ? ? ? ? ? return Regex.Replace(format, pattern, evaluator, RegexOptions.Compiled);

? ? ? ? }

? ? }

?

调用:?var p = new Person {Name="test",Sex="man"};

? ? ? ? ? ? string str = p.ToString("Person : Name : [Name] _ Sex : [Sex]");

? ? ? ? ? ? Console.WriteLine(str);