Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 带or条件的C模式匹配_C#_Pattern Matching - Fatal编程技术网

C# 带or条件的C模式匹配

C# 带or条件的C模式匹配,c#,pattern-matching,C#,Pattern Matching,在使用模式匹配时,是否可以在if语句中使用OR条件 我有一个模式匹配语句,如下所示: if (viewModel is StudentViewModel pageModel) { } 我想检查viewModel是StudentViewModel还是ParentViewModel。不必编写switch语句或另一个if语句就可以实现这一点吗?您可以测试viewModel是否是以下两个类之一: if (viewModel is StudentViewModel || viewModel is Par

在使用模式匹配时,是否可以在if语句中使用OR条件

我有一个模式匹配语句,如下所示:

if (viewModel is StudentViewModel pageModel)
{
}

我想检查viewModel是StudentViewModel还是ParentViewModel。不必编写switch语句或另一个if语句就可以实现这一点吗?

您可以测试viewModel是否是以下两个类之一:

if (viewModel is StudentViewModel || viewModel is ParentViewModel) {
  // ... viewModel is either a StudentViewModel  or a ParentViewModel
}

谢谢你的回复。但是您的答案忽略了pageModel变量。这对我来说很重要,因为它在方法中使用,而viewModel是objectOh类型的哦,是的,对不起,我错过了。由于类型检查发生在运行时,因此无法将c is type varname构造与or/case结合使用,因为变量类型可以解析为两种不同的类型。我认为最好的选择是如果viewModel是StudentViewModel pageModel{},或者如果viewModel是ParentViewModel parentModel{}。或者如果你真的需要共享逻辑,你可以重构这些类来共享一个父类。谢谢@spenster。谢谢你的答复。我现在已经这样做了,我不明白为什么人们会否决一个真正的问题?至少当你投否决票时,如果你对为什么投否决票留下评论,那就太好了