谁能帮我将下面的表达式转换为经典开关,因为我无法使用它?
private static bool TryGetScaleTransform(FrameworkElement frameworkElement, out ScaleTransform scaleTransform)
{
scaleTransform = frameworkElement.LayoutTransform switch
{
TransformGroup transformGroup => transformGroup.Children.OfType<ScaleTransform>().FirstOrDefault(),
ScaleTransform transform => transform,
_ => null
};
return scaleTransform != null;
}
其背后的想法与你所写的几乎相同。这是 C# 7 的语法:
private static bool TryGetScaleTransform(FrameworkElement frameworkElement, out ScaleTransform scaleTransform)
{
switch(frameworkElement.LayoutTransform)
{
case TransformGroup transformGroup:
scaleTransform= transformGroup.Children
.OfType<ScaleTransform>().FirstOrDefault();
break;
case ScaleTransform transform:
scaleTransform = transform;
break;
default:
scaleTransform = null;
break;
}
return scaleTransform != null;
}
上述解决方案需要 C# 7 才能工作。如果您使用的语言版本低于该版本,您必须与自己抗衡
if - else
。
private static bool TryGetScaleTransform(FrameworkElement frameworkElement, out ScaleTransform scaleTransform)
{
if(frameworkElement.LayoutTransform is TransformGroup)
{
scaleTransform = frameworkElement.LayoutTransform.Children
.OfType<ScaleTransform>().FirstOrDefault();
return true;
}
if(frameworkElement.LayoutTransform is ScaleTransform)
{
scaleTransform = frameworkElement.LayoutTransform;
return true;
}
scaleTransform null;
return false;
}