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

标签 c# arrays generics

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

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

类似于:

public static function bool IsOfType(object Obj,params Type[] Types)

然而,这需要以下用法:

if(X.IsOfType(typeof(int),typeof(float))
{...}

我想做这样的事情:

if(X is {int,float})

if(X.IsOfType(int,float))

甚至

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

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

最佳答案

在 C# 10 中,您可以使用模式匹配来测试一个对象的多种类型。

例子:

public bool TestObject<T>(T obj)
{
    if (obj is not null and (int or float or uint))
    {
        // obj is not null and guaranteed to be an int, float or uint 
    }
}

示例 2(如果您想使用该值):

public bool TestIntOrFloat<T>(T obj)
{
    if (obj is not (int or float))
    {
        // obj is neither int or float
    }
    else if (obj is int i)
    {
        // obj is an integer and can be used with the variable 'i'
    }
    else if (obj is float f)
    {
        // obj is a floating number and can be used with the variable 'f'
    }
}

关于C# 根据多种类型检查对象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36604200/

相关文章:

C# 数据表如何对相似的行进行分组

c - 将函数的输出按从高到低的顺序显示

C# 泛型列表联合问题

java - 使程序友好并使用泛型

typescript - 如何根据可选参数的类型确定返回类型

c# - 在创建对象的线程上调用方法

c# - 如何在 C# 中的 Dictionary<K,V> 中获取打包为值的数组大小?

C# 位图对象,颜色显示为透明

java - 如何将 "_INC"(String) 附加到列表中每个元素的末尾?

ios - 向 NSArray 对象添加标签