.Net判斷一個對象是否為數實值型別

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   ar   for   sp   div   

這乍一聽是個很簡單的事,但突然搞起來還真有點無從下手的感覺。

首先當然是通過GetType()方法反射擷取其類型資訊,然後對其進行分析,但是類型資訊Type中並沒有簡單地給出這麼一個屬性進行判斷。

老外給出的方法是:

public static bool IsNumeric(this Type dataType)    {        if (dataType == null)            throw new ArgumentNullException("dataType");        return (dataType == typeof(int)                || dataType == typeof(double)                || dataType == typeof(long)                || dataType == typeof(short)                || dataType == typeof(float)                || dataType == typeof(Int16)                || dataType == typeof(Int32)                || dataType == typeof(Int64)                || dataType == typeof(uint)                || dataType == typeof(UInt16)                || dataType == typeof(UInt32)                || dataType == typeof(UInt64)                || dataType == typeof(sbyte)                || dataType == typeof(Single)               );    }

我勒個去。。。他是想窮舉比對所有已知數實值型別。。。。這麼做應該是可以,就是效能差點並且不雅吧。

而且~他好像還忘了Decimal。。。

我研究了一下這些數實值型別,它們貌似都是結構而非類,而且都有共同的介面:

IFormattable, IComparable, IConvertible

其中IFormattable介面是數實值型別有別於其它幾個基礎類型的介面。

這樣就非常好辦了,代碼如下:

public static bool IsNumericType(this Type o)    {        return !o.IsClass && !o.IsInterface && o.GetInterfaces().Any(q => q == typeof(IFormattable));    }

另外除了基本類型之外還有可空類型Nullable<T>,就是常用的例如double?這種,對於泛型的類型的匹配我不知該怎麼做才好,趕時間就沒深究,用了個偷懶的方法實現了:

public static bool IsNullableNumericType(this Type o)    {        if (!o.Name.StartsWith("Nullable")) return false;        return o.GetGenericArguments()[0].IsNumericType();    }

看吧,只是判斷一下類型名稱是不是以“Nullable”開始,如果是的話再對其第一個泛型參數類型進行上面的判斷,這樣肯定不是100%靠譜的,希望有識之士能夠完善一下這個方法並分享出來哈。

.Net判斷一個對象是否為數實值型別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.