【IT168 评论】ToString方法大概是.Net时被用得最多的方法了,所有类型都,引用的,值的,都传承了这个从祖先Object开始的光荣传统。调用一次ToString,相当于惊堂木“啪”一下,大喝“堂下案犯报上名来”,这家伙就全招了。
可是写程序如查案,形形色色的人都有,对于些记性差,反应迟钝的家伙,就没那么顺利了。梅(枚)举人就是其中之一,来审问下看看:
static void testEnumToString()
{
var day = DayOfWeek.Wednesday;
string value = null;
for (int i = 0; i < 1000000; i++)
{
value = day.ToString();
}
Console.WriteLine(value);
}
{
var day = DayOfWeek.Wednesday;
string value = null;
for (int i = 0; i < 1000000; i++)
{
value = day.ToString();
}
Console.WriteLine(value);
}
整理下结果:
次数 | 1 | 2 | 3 | 4 |
时间(ms) | 7135 | 7009 | 7174 | 7010 |
看上去没什么,不过根据本府以往的断案经验,其中似有猫腻。本着勿枉勿纵,对人民负责的态度,不怕麻烦,另寻突破口:
static void testEnumToString2()
{
var day = DayOfWeek.Wednesday;
string value = null;
for (int i = 0; i < 1000000; i++)
{
switch (day)
{
case DayOfWeek.Friday:
value = "Friday";
break;
case DayOfWeek.Monday:
value = "Monday";
break;
case DayOfWeek.Saturday:
value = "Saturday";
break;
case DayOfWeek.Sunday:
value = "Sunday";
break;
case DayOfWeek.Thursday:
value = "Thursday";
break;
case DayOfWeek.Tuesday:
value = "Tuesday";
break;
case DayOfWeek.Wednesday:
value = "Wednesday";
break;
default:
break;
}
}
Console.WriteLine(value);
}
{
var day = DayOfWeek.Wednesday;
string value = null;
for (int i = 0; i < 1000000; i++)
{
switch (day)
{
case DayOfWeek.Friday:
value = "Friday";
break;
case DayOfWeek.Monday:
value = "Monday";
break;
case DayOfWeek.Saturday:
value = "Saturday";
break;
case DayOfWeek.Sunday:
value = "Sunday";
break;
case DayOfWeek.Thursday:
value = "Thursday";
break;
case DayOfWeek.Tuesday:
value = "Tuesday";
break;
case DayOfWeek.Wednesday:
value = "Wednesday";
break;
default:
break;
}
}
Console.WriteLine(value);
}
呈堂证供一上,满堂皆惊:
次数 | 1 | 2 | 3 | 4 |
时间(ms) | 2 | 1 | 1 | 1 |
我大怒,“大胆狂徒,还不从实招来,不然休怪本府大刑伺候”,梅举人哪见这阵势,浑身哆嗦,头拄地跪着,一会儿没了声息,衙役拖起一看,竟吓晕过去了。
“大人,是否冷水浇醒用刑”,我想,看案犯这德性,也挨不住几板子,说“先到案犯家里,搜查证据”。能干的捕头Reflector领命,一下子找到了线索:
public override string ToString()
{
return InternalFormat((RuntimeType) base.GetType(), this.GetValue());
}
private static string InternalFormat(RuntimeType eT, object value)
{
if (eT.IsDefined(typeof(FlagsAttribute), false))
{
return InternalFlagsFormat(eT, value);
}
string name = GetName(eT, value);
if (name == null)
{
return value.ToString();
}
return name;
}
{
return InternalFormat((RuntimeType) base.GetType(), this.GetValue());
}
private static string InternalFormat(RuntimeType eT, object value)
{
if (eT.IsDefined(typeof(FlagsAttribute), false))
{
return InternalFlagsFormat(eT, value);
}
string name = GetName(eT, value);
if (name == null)
{
return value.ToString();
}
return name;
}
果然不出所料,案犯肆无忌惮地用了反射,至此案件真相大体明了。如IsDefined和GetName两处,深究下去,触目惊心,令人发指。
可惜天下人,有多少还被蒙在鼓里,浑然不觉,荼毒流弊甚为深远。正本清源之路,漫漫修远。本府一已之力,深感力不从心,望和天下有志之士一道,扬善锄恶,共致太平盛世。