当前位置: 移动技术网 > IT编程>开发语言>c# > C#中使用IFormattable实现自定义格式化字符串输出示例

C#中使用IFormattable实现自定义格式化字符串输出示例

2019年07月18日  | 移动技术网IT编程  | 我要评论

iformattable接口提供了tostring()方法的定义,使用该方法可以将对象的值按照指定的格式转化成字符串的功能。

下面是tostring()方法的完整定义。

复制代码 代码如下:

string tostring( string format, iformatprovider formatprovider ) 

其中:

第一个参数告诉方法需要何种格式的输出,而第二个iformatprovider的参数则允许类型的使用者自定义格式化方法,在本文实现的tostring()方法中,并没有使用到第二个参数。关于iformatprovider接口请阅读文章《icustomformatter及iformatprovider接口用法揭秘》,本文不做过多说明。下面是完整的实例代码。

using system;
using system.globalization;


namespace greetingexample
{
  public class greeting : iformattable
  {
    private string name;
    public greeting(string name)
    {
      this.name = name;
    }


    public override string tostring()
    {
      return this.tostring("cn",cultureinfo.currentculture);
    }


    public string tostring(string format)
    {
      return this.tostring(format,cultureinfo.currentculture);
    }


    public string tostring(string format, iformatprovider provider)
    {
      if (string.isnullorempty(format)) format = "cn";
      if (provider == null) provider = cultureinfo.currentculture;
      switch (format.toupper())
      {
        case "cn":
        case "tw":
          return "你好," + name.tostring();
        case "us":
        case "gb":
          return "hello," + name.tostring();
        case "jp":
          return "こんにちは," + name.tostring();
        default:
          throw new formatexception(string.format("the {0} format string is not supported.", format));
      }
    }
  }
}
using system;


namespace greetingexample
{
  class program
  {
    static void main(string[] args)
    {
      greeting greeting = new greeting("三五月儿");
      console.writeline(greeting.tostring("cn"));
      console.writeline(greeting.tostring("us"));
      console.writeline(greeting.tostring("jp"));
    }
  }
}

下面是代码的运行结果。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网