【发布时间】:2011-09-27 16:24:05
【问题描述】:
使用 .Net Compact Framework 2.0,如何验证整数(Compact Framework 不支持Int32.TryParse)?
【问题讨论】:
标签: c# compact-framework
使用 .Net Compact Framework 2.0,如何验证整数(Compact Framework 不支持Int32.TryParse)?
【问题讨论】:
标签: c# compact-framework
有同样的问题。试试这个:
static bool numParser(string s)
{
foreach (char c in s)
if (!char.IsNumber(c))
return false;
return true;
}
【讨论】:
In addition to including digits, numbers include characters, fractions, subscripts, superscripts, Roman numerals, currency numerators, and encircled numbers.
static bool TryParseImpl(string s, int start, ref int value)
{
if (start == s.Length) return false;
unchecked {
int i = start;
do {
int newvalue = value * 10 + '0' - s[i++];
if (value != newvalue / 10) { value = 0; return false; } // detect non-digits and overflow all at once
value = newvalue;
} while (i < s.Length);
if (start == 0) {
if (value == int.MinValue) { value = 0; return false; }
value = -value;
}
}
return true;
}
static bool TryParse(string s, out int value)
{
value = 0;
if (s == null) return false;
s = s.Trim();
if (s.Length == 0) return false;
return TryParseImpl(s, (s[0] == '-')? 1: 0, ref value);
}
【讨论】:
public static bool IsInt(string s) {
bool isInt = true;
for (int i = 0; i < s.Length; i++) {
if (!char.IsDigit(s[i])) {
isInt = false;
break;
}
}
return isInt;
}
例子:
string int32s = "10240";
bool isInt = IsInt(int32s); // resolves true
或者:
string int32s = "1024a";
bool isInt = IsInt(int32s); // resolves false
【讨论】:
如果您的号码是一个字符串,您可以获取字符串 char 数组并检查 Char.IsNumber 是否对每个字符都为真。
检查第一个字符是否为“-”以允许负数,如果需要它们并添加一个 try/catch 块以防止数字超出范围(int min / max value)。如果您不必处理接近最小/最大的数字,请考虑设置最大长度(可能是 6-7 位),然后只需检查 string.Length。
如果您只遇到有效的 ints 和无效的机会是罕见的无效操作,您可能会坚持使用简单的 try/catch 块(请参阅我对 ctakes 答案的评论)。
【讨论】:
"4697357344197412413772951060481818689355170685471900754944636793" 呢?
Char.IsNumber 绝对是错误的测试。 “除了包括数字外,数字还包括字符、分数、下标、上标、罗马数字、货币分子和带圆圈的数字。”
“验证”是什么意思?你的意思是解析而不抛出?
static bool TryParse(string s, out int value)
{
try
{
value = int.Parse(s);
return true;
}
catch
{
value = 0;
return false;
}
}
【讨论】: