如何将 C#8 switch 表达式转换为经典 switch?

问题描述 投票:0回答:1

谁能帮我将下面的表达式转换为经典开关,因为我无法使用它?

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# switch-statement .net-4.5 c#-5.0 c#-8.0
1个回答
4
投票

其背后的想法与你所写的几乎相同。这是 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;
}
© www.soinside.com 2019 - 2024. All rights reserved.