有没有办法将类型数组传递给“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/