如果可以將類型作爲泛型參數傳遞,那麼有一個解決方案。不幸的是,C#不支持可變泛型。您必須爲每個通用元素定義函數。
public static bool IsOfType<T>(this object obj) => obj is T;
public static bool IsOfType<T1, T2>(this object obj) => obj is T1 || obj is T2;
public static bool IsOfType<T1, T2, T3>(this object obj) => obj is T1 || obj is T2 || obj is T3;
public static bool IsOfType<T1, T2, T3, T4>(this object obj) => obj is T1 || obj is T2 || obj is T3 || obj is T4;
public static bool IsOfType<T1, T2, T3, T4, T5>(this object obj) => obj is T1 || obj is T2 || obj is T3 || obj is T4 || obj is T5;
public static bool IsOfType<T1, T2, T3, T4, T5, T6>(this object obj) => obj is T1 || obj is T2 || obj is T3 || obj is T4 || obj is T5 || obj is T6;
public static bool IsOfType<T1, T2, T3, T4, T5, T6, T7>(this object obj) => obj is T1 || obj is T2 || obj is T3 || obj is T4 || obj is T5 || obj is T6 || obj is T7;
public static bool IsOfType<T1, T2, T3, T4, T5, T6, T7, T8>(this object obj) => obj is T1 || obj is T2 || obj is T3 || obj is T4 || obj is T5 || obj is T6 || obj is T7 || obj is T8;
我懷疑你會需要超過8種類型,但如果你這樣做,只需定義更多的重載。
如果您正在編寫必須執行的代碼很多類型檢查都是針對* basic *類型的,這與CLR本身一起使用的常用方法是在['Type.GetTypeCode'](https://msdn.microsoft.com/library/system。 type.gettypecode)。如果你發現自己對非基本類型做了很多事情,那麼你的代碼可能有些問題,首先它需要一個簡寫。 –
爲了進一步@JeroenMostert評論,這是如何[檢查類型是數字](https://stackoverflow.com/questions/1749966/c-sharp-how-to-determine-whether-a-type-is-一個號碼)。 – ryanyuyu
只需創建IsNumeric擴展功能即可。你不太可能真的需要檢查許多任意類型的對象。 – Evk