请帮助解释此代码 [英] please help with explanation of this code

查看:70
本文介绍了请帮助解释此代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助解释此代码:

please help with explanation of this code:

if (Convert.ToInt16(day) < 10 && day.Length == 1)
{
   day = String.Format("0{0}", day);
}
//month = "09";
if (Convert.ToInt16(month) < 10 && month.Length == 1)
{
   month = String.Format("0{0}", month);
}

推荐答案

它将单个数字转换为两位数字,因此1变为01但是12 保持12,01保持01。



如果day为3,则Convert.ToInt16为3,因此检查是day的数值为3,day字符串的长度为1.这意味着它只对3这样的东西感兴趣,但忽略03,因为03的长度为2.当它找到时它想要修改的字符串在前面添加一个零,这就是string.format的作用。



有更有效的方法可以做到这一点。
It converts single digit numbers to double digit numbers, so "1" becomes "01" but "12" remains "12" and "01" remains "01".

if "day" is "3" then Convert.ToInt16 is 3 so it is checking that the numeric value of "day" is 3 and that the length of the "day" string is 1. This means it is only interesting in things like "3" but will ignore "03" as the length of 03 is 2. When it finds a string it wants to amend it adds a zero in front which is what string.format does.

There are more efficient ways of doing this.


这段代码只是确保(但不是最好的方式)月份和日期的数字将是2个字符长。



但这很愚蠢。日和月应该是整数,而不是字符串;并且以这种方式显示具有给定位数的整数:

This code simply ensures (but not the best way) that month and day numbers will be 2 characters-long.

But that is silly. Day and month should be integers, not strings; and displaying an integer with a given number of digits is done this way:
// Remember that day and month variables here are integers
// (whereas they are strings in your question)
string dayString = day.ToString("D2");
string monthString = month.ToString("D2");



不幸的是,现在经常看到使用字符串类型而不是正确的类型;这是一个应该尽快打好的可怕习惯。



希望这会有所帮助。


Using string type instead of the correct type is seen very often these days, unfortunately; that is a terrible habit that should be fought as soon as possible.

Hope this helps.


这篇关于请帮助解释此代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆