我需要發現一個類型。如何發現帶反射的未知類型類型?(如果是數字或字母數字)
場景:
我從DB收到未知類型,並希望classificate如果他是數字或字母我可怎麼辦呢?
例如:
public object GetUnkown(){....};
var x = GetUnkown();
x是數字還是字母數字?只有兩種可能性。
我需要發現一個類型。如何發現帶反射的未知類型類型?(如果是數字或字母數字)
場景:
我從DB收到未知類型,並希望classificate如果他是數字或字母我可怎麼辦呢?
例如:
public object GetUnkown(){....};
var x = GetUnkown();
x是數字還是字母數字?只有兩種可能性。
爲了測試它是否可以被解析爲整數:
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
}
.hehe snap;).. – Russell 2011-03-29 03:23:10
@Russell笑了起來? – 2011-03-29 03:26:20
你可以關閉括號嗎? :) – TheEvilPenguin 2011-03-29 04:30:28
有幾個方法可以做到這一點。如果你從數據庫中獲得不同的數據類型,那麼你可以像這樣做一個類型比較;
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);
這是詳盡的,但它會給你正確的答案。
如果您總是從數據庫中獲取一個字符串,那麼您可以使用一些內置的解析函數,這些解析函數將在大部分時間內運行。
// 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);
十進制在.NET(內置類型)中具有最廣泛的數字範圍,所以這將涵蓋很多情況。但是,如果您的「號碼」超出了範圍,它仍然可能失敗。例如,假設你有
string n = "5123123189461894481984885646158419999";
decimal d;
bool isNumeric = decimal.TryParse(n, out d);
即使x表示數字,「ISNUMERIC」會回來爲假,因爲數字是十進制類型的範圍之外。幸運的是,這些情況非常罕見,因此您不必訴諸其他更強烈的字符串解析方法來判斷它是否是數字。 (我現在不打算討論這個問題。)
你的問題令人驚訝的意義不大。請提供更多細節。 – SLaks 2011-03-29 03:19:24