C#整数验证compactframework [英] c# integer validation compactframework
本文介绍了C#整数验证compactframework的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用.NET Compact Framework 2.0的,我怎么能验证一个整数( Int32.TryParse
不支持Compact Framework中)?
解决方案
静态布尔TryParseImpl(字符串s,诠释开始,楼盘int值)
{
如果(开始== s.Length)返回false;
选中{
INT I =启动;
做{
INT NEWVALUE =值* 10 +'0' - S [我++];
如果(值= NEWVALUE / 10!){值= 0;返回false; } //检测到非数字和溢出一下子
值= NEWVALUE;
},而(I< s.Length);
如果(开始== 0){
如果(价值== int.MinValue){值= 0;返回false; }
值= - 值;
}
}
返回真;
}
静态布尔的TryParse(字符串s,出int值)
{
值= 0;
如果(S == NULL)返回false;
S = s.Trim();
如果(s.Length == 0)返回false;
返回TryParseImpl(S,(S [0] ==' - ')1:0,参考值);
}
Using the .Net Compact Framework 2.0, how can I validate an integer (Int32.TryParse
is not supported on the Compact Framework)?
解决方案
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);
}
Demo: http://ideone.com/PravA
这篇关于C#整数验证compactframework的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文