문제

Is it possible to check for negative number using Int32.TryParse?

int defaultTop;
displayTop = (Int32.TryParse(DisplayTop, out defaultTop) ? Convert.ToInt32(DisplayTop) : 1000 );
도움이 되었습니까?

해결책

Why not use UInt32.TryParse(DisplayTop, out defaultTop)?

This will return true if the number is 0 or positive, and false if negative.

다른 팁

Try this

int defaultTop;
var isValidInt = Int32.TryParse(DisplayTop, out defaultTop);
displayTop = isValidInt && defaultTop >= 0 ? defaultTop : 1000;

You can't do that with TryParse alone, you will have to check the value of defaultTop independently. If you want it all in a single line you can try:

displayTop = ((Int32.TryParse(DisplayTop, out defaultTop) && defaultTop >= 0) ? defaultTop : 1000 );

Use Math.Max:

displayTop = Math.Max(1,(Int32.TryParse(DisplayTop, out defaultTop) ? Convert.ToInt32(DisplayTop) : 1000 ));

Granted, such a long expression is somewhat ugly, but it works.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top