C#ToString常⽤技巧总结
ToString是在开发中最常⽤的操作,其作⽤是将其它类型以字符串类型表⽰。例如:
int i=2;
i.ToString() //”2″
Object o = new Object();
o.ToString(); // 返回对象类型 System.Object
但是ToString也并⾮就这么简单。因为ToString实现⾃Object类,⽽Object类是⼀切类的基类。其它的类继承⾃Object,⾃然也就实现了ToString⽅法。但是也可以重写ToString⽅法。这也就衍⽣了其它的使⽤。如果我们运⽤合理的话,将会使我们的开发⾮常的⽅便。例如在开发中常⽤到的:
⼀.格式化输出,包含值类型,DateTime,GUID等,ToString()中接受参数,根据参数输出指定格式。
为实现格式化输出,在相关的类型中,重写ToString()为
public string ToString(string format) format 接收的参数,按指定的格式输出。接受参数,如”C”,”D”,”E”,”
等.
public string ToString(string format,IFormatProvider provider) format 接收的参数,provider 为语⾔⽂化如zh-CN 表⽰中⽂,en-US 表⽰美国英语
1.值类型,有时我们需要将值类型按照格式化输出,如输出为货币类型,我们只需要在ToString()中指定format为”C”,如果需要输出美元符号,可以将provider指定为en-US,例如
float f = 2000.12f;
f.ToString(“c”, CultureInfo.CreateSpecificCulture(“en-US”)); //输出为$2,000.12
值类型中常⽤的参数有:
格式化参数说明
C货币符号
D⼗进制表⽰,后跟数字表占位符如
25.ToString(“D3”) ; =025
等价于 25.ToString(“000”);
N易读性数值表⽰法 ,⽤逗号分隔⼤型数
值。如
123456.ToString(“N”); //123,456
P百分号
X数值的16进制表⽰,X后跟数字表⽰⽤⼏
位表⽰16进制。如10.ToString(“X8”);
//0000000A
F指定⼩数点位置,四舍五⼊
E指数表⽰,后跟数字表⽰⼩数点位数
G数值的⼀般表⽰格式,后跟数字为截取
数值长度
我们可以⽤代码测试格式化参数的使⽤,如下所⽰:
string[] formatTypes = {"C","N","P","F2","E2","G4"};
double d = 1234.6789;
foreach(string type in formatTypes)
{
Console.WriteLine(string.Format("{0}.ToString(\"{1}\")={2}",d,type,d.ToString(type)));
}
测试输出
2.DateTime,格式化参数主要⽤于⽇期时间的格式化输出。DateTime.Now的默认格式为G。参数有⼀部分区分⼤⼩写。如下所⽰
使⽤的代码
string[] dateTimeTypes = { "d", "D", "f", "F", "g", "G", "m","M", "o", "O",
"R","r", "s", "t", "T", "u", "U", "y","Y" };
foreach(string type in dateTimeTypes)
{
Console.WriteLine(string.Format("{0}:{1}", type.PadLeft(2,''),DateTime.Now.ToString(type, CultureInfo.CreateSpecificCulture("zh-CN")))); //设置中国的⽇期格式}
测试输出:
3.GUID,GUID为在开发过程中常⽤来代表唯⼀标⽰。在GUID 类型中,格式化参数主要有:
string[] guidTypes={"N","D","B","P","X"};
foreach(string type in guidTypes)
{
Console.WriteLine(string.Format("{0}",Guid.NewGuid().ToString(type).PadLeft(2,'')));
}
输出结果:
⼆.ToString的重写,C#中的任何对象都继承了ToString()⽅法。在⾃定义类中如果需要重写ToString()⽅法,只需要在类中加⼊:public override string ToString(){}
⽽⽀持格式化参数的ToString()需要继承IFormattable接⼝,并实现
public string ToString(string format,IFormatProvider provider)⽅法
下⾯以People,Peoples类说明如何重写ToString()。本例只是说明ToString()的⽤法,所以并没有与数据库交互。
class People
{
public People(string name,string address)
{
this.Name = name;
this.Address = address;
}
public string Name { set; get; }
public string Address { set; get; }
}
class Peoples:IEnumerable,IFormattable
{
private List<People> _peoples;
private StringBuilder _sb;
public Peoples()
{
_peoples = new List<People>();
}
public void Add(People people)
{
_peoples.Add(people);
}c++string类型
public IEnumerator GetEnumerator()
{
foreach(People p in _peoples)
{
yield return p;
}
}
//重写ToString()
public override string ToString()
{
return GetContent(_peoples);
}
//重写带参ToString()
public string ToString(string format)
{
return ToString(format, CultureInfo.CreateSpecificCulture("zh-CN"));
}
//重写带参ToString()
public string ToString(string format, IFormatProvider provider)
{
IEnumerable<People> ps = _peoples;
if (format.ToUpperInvariant() == "B")
{
ps = from p in _peoples where p.Address == "北京"select p;
}
else if (format.ToUpperInvariant() == "S")
{
ps = from p in _peoples where p.Address == "上海"select p;
}
return GetContent(ps);
}
private string GetContent(IEnumerable<People> peoples)
{
_sb = new StringBuilder();
foreach(People p in peoples)
{
_sb.AppendLine(string.Format("{0}:{1}", p.Name, p.Address));
}
return _sb.ToString();
}
}
static void Main(string[] args)
{
Peoples peoples = new Peoples(){new People("zhangsan","北京"),new People("lisi","上海"),new People("wangwu","北京"),new People("naliu","北京")}; Console.WriteLine("本站会员有:");
Console.WriteLine(peoples.ToString());
Console.WriteLine("北京的会员有:");
Console.WriteLine(peoples.ToString("B"));
Console.WriteLine("上海的会员有:");
Console.WriteLine(peoples.ToString("S"));
Console.ReadLine();
}
输出结果:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论