C# 根据多种类型检查对象类型

Jef*_*nak 8 c# arrays generics

有没有办法将类型数组传递给“is”运算符?

我正在尝试简化针对多种类型检查对象的语法。

就像是:

public static function bool IsOfType(object Obj,params Type[] Types)
Run Code Online (Sandbox Code Playgroud)

但是,这需要以下用法:

if(X.IsOfType(typeof(int),typeof(float))
{...}
Run Code Online (Sandbox Code Playgroud)

我想做类似的事情:

if(X is {int,float})
Run Code Online (Sandbox Code Playgroud)

或者

if(X.IsOfType(int,float))
Run Code Online (Sandbox Code Playgroud)

甚至

public static bool ISOfType<T[]>(this object Obj){...}
if(X.ISOfType<int,float>())
Run Code Online (Sandbox Code Playgroud)

我认为他们都是不可能的。

The*_*kis 2

如果您同意将类型作为通用参数传递,那么有一个解决方案。不幸的是,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;
Run Code Online (Sandbox Code Playgroud)

我怀疑您是否需要超过 8 个类型,但如果需要,只需定义更多重载即可。