• Named Formats!


    原文发布时间为:2011-06-26 —— 来源于本人的百度文章 [由搬家工具导入]

    using System;
    using System.Text;
    using System.Web;
    using System.Web.UI;

    namespace StringLib
    {
    public static class HenriFormatter
    {
    public static string FormatWith(this string format, object source)
    {
    if (format == null)
    throw new ArgumentNullException("format");

    var result = new StringBuilder(format.Length * 2);
    var expression = new StringBuilder();

    var e = format.GetEnumerator();
    while (e.MoveNext())
    {
    var ch = e.Current;
    if (ch == '{')
    {
    while (true)
    {
    if (!e.MoveNext())
    throw new FormatException();

    ch = e.Current;
    if (ch == '}')
    {
    result.Append(OutExpression(source, expression.ToString()));
    expression.Length = 0;
    break;
    }
    if (ch == '{')
    {
    result.Append(ch);
    break;
    }
    expression.Append(ch);
    }
    }
    else if (ch == '}')
    {
    if (!e.MoveNext() || e.Current != '}')
    throw new FormatException();
    result.Append('}');
    }
    else
    {
    result.Append(ch);
    }
    }

    return result.ToString();
    }

    private static string OutExpression(object source, string expression)
    {
    string format = "{0}";

    int colonIndex = expression.IndexOf(':');
    if (colonIndex > 0)
    {
    format = "{0:" + expression.Substring(colonIndex + 1) + "}";
    expression = expression.Substring(0, colonIndex);
    }

    try
    {
    return DataBinder.Eval(source, expression, format) ?? string.Empty;
    }
    catch (HttpException)
    {
    throw new FormatException();
    }
    }
    }

    }

    ===============

    MembershipUser user = Membership.GetUser();

    "{UserName} last logged in at {LastLoginDate}".FormatWith(user);

    output===》 njwu last logged in at 2010年1月6日08:07:39

    =============

    "{CurrentTime} - {UrL}".FormatWith(new { CurrentTime = DateTime.Now, url = "http://hi.baidu.com/handboy" });

    output==》2010年1月6日08:07:39 - http://hi.baidu.com/handboy

    ===================

    "{{{UserName}}} last logged in at {LastLoginDate}".FormatWith(user);

    output==> {njwu} last logged in at 2010年1月6日08:07:39

    ================

    Console.WriteLine("{date:yyyy-MM-dd},{url}".FormatModel(new { date = DateTime.Now, url = "http://hi.baidu.com/handboy" }));

    output==> 2011-06-26,http://hi.baidu.com/handboy

    ==================

  • 相关阅读:
    Winform中实现FTP客户端并定时扫描指定路径下文件上传到FTP服务端然后删除文件
    NodeRED简介与Windows上安装、启动和运行示例
    CentOS7中后台运行NodeRED(关闭窗口也能访问服务)
    CentOS7中使用PM2设置NodeRED开机自启动
    Windows上编译github源码方式运行NodeRED,以及离线迁移安装NodeRED
    升级npm
    FastAPI 学习之路(十八)表单与文件
    FastAPI 学习之路(十七)上传文件
    ArcGIS9.2新功能之File Geodatabase(对比PGDB) 【转】
    Catalog无法连接Server
  • 原文地址:https://www.cnblogs.com/handboy/p/7182584.html
Copyright © 2020-2023  润新知