how discover unkown type type with reflection?(if is Numeric or Alphanumeric)
i need discover a type.
scenario:
I receive from DB a unkown type and want classificate if him is Numeric or Alphanumeric how i can do that?
eg:
public object GetUnkown(){....};
var x = GetUnkown();
x is numeric or alphanumeric?have only two these poss开发者_JS百科ibilities.
To test if it can be parsed as an integer:
int xInt;
CultureInfo culture = new CultureInfo("en-US");
bool isInteger = int.TryParse(x, NumberStyles.AllowThousands, culture, out xInt);
if (isInteger)
{
}
else
{
string xString = x.ToString();
}
int numeric;
if (int32.TryParse(value, out numeric))
{
... numeric processing
}
else
{
... alpha numeric processing
}
There are a couple of ways to do this. If you are getting different data types from the database, then you can do a type comparison like so;
Type t = x.GetType();
bool isNumeric t == typeof(sbyte) ||
t == typeof(byte) ||
t == typeof(short) ||
t == typeof(ushort) ||
t == typeof(int) ||
t == typeof(uint) ||
t == typeof(long) ||
t == typeof(ulong) ||
t == typeof(float) ||
t == typeof(double) ||
t == typeof(decimal);
This is exhaustive, but it will give you the correct answer.
If you are always getting a string from the database, then you can use some of the built-in parsing functions that will work MOST of the time.
// DO NOT USE 'int.TryParse()' as it will FAIL for any non-integer number, i.e. "123.456"
decimal d;
bool isNumeric = decimal.TryParse(x, out d);
Decimal has the widest range of numbers in .NET (of the built in types) so this will cover a lot of cases. However it can still fail if your 'number' lies outside of its range. For example, let's say that you have
string n = "5123123189461894481984885646158419999";
decimal d;
bool isNumeric = decimal.TryParse(n, out d);
Even though x represents a number, 'isNumeric' will come back as false because the number is outside of the range of the decimal type. Lucky for you, these cases are exceedingly rare, and so you won't have to resort to some other, more intense string parsing approach to tell if it is a number or not. (Which I am not going to cover at this time.)
精彩评论