C#中使用IFormattable實(shí)現(xiàn)自定義格式化字符串輸出示例
IFormattable接口提供了ToString()方法的定義,使用該方法可以將對象的值按照指定的格式轉(zhuǎn)化成字符串的功能。
下面是ToString()方法的完整定義。
string ToString( string format, IFormatProvider formatProvider )
其中:
第一個參數(shù)告訴方法需要何種格式的輸出,而第二個IFormatProvider的參數(shù)則允許類型的使用者自定義格式化方法,在本文實(shí)現(xiàn)的ToString()方法中,并沒有使用到第二個參數(shù)。關(guān)于IFormatProvider接口請閱讀文章《ICustomFormatter及IFormatProvider接口用法揭秘》,本文不做過多說明。下面是完整的實(shí)例代碼。
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")); } } }
下面是代碼的運(yùn)行結(jié)果。
相關(guān)文章
C#使用oledb導(dǎo)出數(shù)據(jù)到excel的方法
這篇文章主要介紹了C#使用oledb導(dǎo)出數(shù)據(jù)到excel的方法,結(jié)合實(shí)例形式分析了C#操作oledb導(dǎo)出數(shù)據(jù)的相關(guān)技巧與注意事項(xiàng),需要的朋友可以參考下2016-06-06C#如何將查詢到的數(shù)據(jù)庫里面的數(shù)據(jù)輸出到textbox控件
這篇文章主要介紹了C#如何將查詢到的數(shù)據(jù)庫里面的數(shù)據(jù)輸出到textbox控件問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07