c# - 如何将 int 转换为选择的枚举?

标签 c# .net asp.net-mvc enums

以前的一位开发人员(不再与我们合作,所以我不能问他)做了一些非常巧妙的事情,我真的不明白。我们有这个枚举:

   [Flags]
    public enum SidingTypePreference
    {
        [Value(Name = "Vinyl")]
        Vinyl = 1,
        [Value(Name = "Metal or Aluminum")]
        MetalOrAluminum = 2,
        [Value(Name = "Composite")]
        Composite = 4,
        [Value(Name = "Wood")]
        Wood = 8,
        [Value(Name = "Other")]
        Other = 16
    }

在数据库中,SidingTypes 存储为单个 int,它是所有选定值的总和。

enter image description here

在模型中:

public SidingTypePreference? SidingTypes { get; set; }

在 Controller 中,table 只是查询的一行结果:

Model.SidingTypes = table.SidingTypes

在 View 中:

@Html.EditorFor(m => Model.SidingTypes, new { @class = "form-control input-sm", GroupID = "SidingTypePreference", Cols = 1 })

但是,这是我不明白的部分。假设 SidingTypes = 10。通过某种巫毒魔法,该 int 被翻译成:

<input type="checkbox" class="..." name="SidingTypes_0" value="1">  Vinyl
<input type="checkbox" class="..." name="SidingTypes_1" value="2" checked>  Metal or Aluminum
<input type="checkbox" class="..." name="SidingTypes_2" value="4"> Composite
<input type="checkbox" class="..." name="SidingTypes_3" value="8" checked> Wood
<input type="checkbox" class="..." name="SidingTypes_4" value="16"> Other

(为了防止需要滚动而对类进行了编辑,但它们都是“lookup-checkbox-SidingTypes”。)

根据该 int 的值,它知道哪些已检查,哪些未检查。

第一个问题:这是 native .NET 吗?或者我需要找到一些扩展方法或模板吗?

第二个问题:我需要做的,独立于其他任何事情,是构建一个方法来确定是否选择了一个枚举。

类似于:

private bool IsSelected(int SidingTypes, SidingTypePreference sidingTypePreference)
{
  ... ?? ...
  return true or false;
}

最佳答案

Is this native .NET?

部分是。具有 Flags 属性的枚举将值分解为构成该复合值的等效位(例如 10 = 2 + 8)

将该值转换为一组复选框不是原生的。我怀疑项目中某处有一个自定义模板将枚举值转换为一组复选框

How do I determine if an enum is selected.

只需使用位运算:

private bool IsSelected(int SidingTypes, SidingTypePreference sidingTypePreference)
{
  return (SidingTypes & (int)sidingTypePreference) != 0;
}

由于 & 运算符将返回一个数字,其中包含在 SidingTypessidingTypePreference 中“选择”的位。如果没有标志匹配,结果将全为零;所以除 0 以外的任何数字都表示匹配。

关于c# - 如何将 int 转换为选择的枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41987793/

相关文章:

c# - 获取网站服务的 tcp 端口

c# - 使用 TextWriter.Synchronized 或锁定多线程文件 IO - C# WPF .net 4.5

c# - 如何在 Java 中编写泛型方法

.net - 开始解耦对象的最佳位置

javascript - 我的表使用 Jquery Table Sorter 获取重复的行

c# - 获取 <> 之间的值,其中包含动态数字

c# - .NET 中的多线程 - 在后台实现计数器

c# - 关于从异步方法同步调用 CPU 绑定(bind)方法的困惑

c# - 为什么 ASP.NET Identity 返回 401 而不是重定向到登录页面?

asp.net-mvc - datatype.text 验证什么?