如何将枚举映射到 class 属性

How do I map enums to a class property

我有一个包含功能名称的枚举,例如

public enum FeatureNames{
  [Description("Amazing Feature")]
  AmazingFeature,
  [Description("Amazing New Feature")]
  AmazingNewFeature
}

我有一个域实体,它具有表示每个功能的属性,指示该功能是打开还是关闭

public class CompanyAccount{
  public bool IsAmazingFeatureEnabled{get;set;}
  public bool IsAmazingNewFeatureEnabled{get;set;}
}

这就是现有应用程序的编写方式,因此此时我不想对数据库进行重大更改。所以现在我正在尝试编写一个通用方法,该方法将接受一个字符串或枚举值指示功能,并检查是否启用了与相同功能匹配的 属性(true 或 false)。

public bool IsEnabled(FeatureNames featureName){
  if(featureName is FeatureNames.AmazingFeature){
    return companyAccount.IsAmazingFeatureEnabled;
  }
  else if(featureName is FeatureNames.AmazingNewFeature){
    return companyAccount.IsAmazingNewFeatureEnabled;
  }

有没有更好的方法来处理这个问题?我们可以避免 if 条件吗?

您可以使用 switch expression (C# 8.0)

public bool IsEnabled(FeatureNames featureName) =>
    featureName switch {
        FeatureNames.AmazingFeature => companyAccount.IsAmazingFeatureEnabled,
        FeatureNames.AmazingNewFeature => companyAccount.IsAmazingNewFeatureEnabled,
        _ => false
    };

或在默认情况下使用 throw expression

        _ => throw new NotImplementedException($"{featureName} not implemented")

另一种方法是将枚举转换为 flags enum 并添加 属性 返回状态作为标志集。

[Flags]
public enum FeatureNames {
    None = 0,
    AmazingFeature = 1,
    AmazingNewFeature = 2 // use powers of 2 for all values
}
public class CompanyAccount{
 public bool IsAmazingFeatureEnabled { get; set; }
 public bool IsAmazingNewFeatureEnabled { get; set; }

 public FeatureNames State {
   get {
     var flags = FeatureNames.None;
     if (IsAmazingFeatureEnabled) flags = flags | FeatureNames.AmazingFeature; 
     if (IsAmazingNewFeatureEnabled) flags = flags | FeatureNames.AmazingNewFeature; 
     return flags;
   }
 }
}

然后你可以用

测试状态
if (companyAccount.State.HasFlag(FeatureNames.AmazingFeature)) ...

使用标志枚举,我们可以扭转局面,将状态存储为标志,然后将逻辑放入布尔属性(此处仅显示一个 属性):

private FeatureNames _state;

public bool IsAmazingFeatureEnabled
{
    get => _state.HasFlag(FeatureNames.AmazingFeature);
    set => _state = value 
        ? _state | FeatureNames.AmazingFeature
        : _state & ~FeatureNames.AmazingFeature;
}