You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C#11 switch表达式匹配非常量FontWeight实现CSS转换?

将WPF FontWeight转换为CSS值的C#11实现方案

你遇到的错误是因为C# switch表达式的模式匹配要求case标签必须是编译时常量,而FontWeights.Bold这类是预定义的FontWeight结构体实例,并非编译期可确定的常量值,因此无法直接作为case标签。以下是两种可行的解决方法:

方法一:使用when子句结合值相等判断

通过_ when模式先匹配任意值,再利用FontWeight的Equals方法判断是否与目标实例相等(FontWeight结构体的相等逻辑是比较内部的Weight属性值,结果可靠):

using System.Globalization;
using System.Windows;

string ToCssValue(FontWeight value) => value switch
{
    _ when value.Equals(FontWeights.Bold) => "bold",
    _ when value.Equals(FontWeights.ExtraBold) => "bolder",
    _ when value.Equals(FontWeights.Normal) => "normal",
    _ when value.Equals(FontWeights.Light) => "lighter",
    _ => value.ToOpenTypeWeight().ToString(CultureInfo.InvariantCulture),
};

方法二:直接匹配Weight属性的数值(推荐)

FontWeights的预定义实例对应固定的Weight数值:

  • FontWeights.Normal → 400
  • FontWeights.Light → 300
  • FontWeights.Bold → 700
  • FontWeights.ExtraBold → 800

直接匹配这个int类型的数值,既符合switch表达式的常量要求,又避免了额外的Equals调用,性能更优:

using System.Globalization;
using System.Windows;

string ToCssValue(FontWeight value) => value.Weight switch
{
    700 => "bold",
    800 => "bolder",
    400 => "normal",
    300 => "lighter",
    _ => value.ToOpenTypeWeight().ToString(CultureInfo.InvariantCulture),
};

内容的提问来源于stack exchange,提问作者Dan Stevens

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 09:18:26