以前的一位开发人员(不再与我们合作,所以我不能问他)做了一些非常巧妙的事情,我真的不明白。我们有这个枚举:
[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,它是所有选定值的总和。
在模型中:
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;
}
由于 &
运算符将返回一个数字,其中包含在 SidingTypes
和 sidingTypePreference
中“选择”的位。如果没有标志匹配,结果将全为零;所以除 0 以外的任何数字都表示匹配。
关于c# - 如何将 int 转换为选择的枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41987793/