iformattable接口提供了tostring()方法的定义,使用该方法可以将对象的值按照指定的格式转化成字符串的功能。
下面是tostring()方法的完整定义。
其中:
第一个参数告诉方法需要何种格式的输出,而第二个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")); } } }
下面是代码的运行结果。
如对本文有疑问, 点击进行留言回复!!
使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序)
C#实现获取本地内网(局域网)和外网(公网)IP地址的方法分析
网友评论