[英]C# with EF enum, lookup-table and the Value to pass it?
我正在接手一個C#項目,我遇到了一個我不熟悉的概念。
該項目使用EF從枚舉中創建查找表。 UI正在接受多選輸入,但接收模型接受枚舉類型,而不是列表/數組或其他暗示復數的東西。
枚舉似乎有一些遞歸關系
public enum Options
{
None = 0,
[Display(Name = @"On-site Security")]
OnSiteSecurity = 1 << 0,
[Display(Name = @"Gated Entry")]
GatedEntry = OnSiteSecurity << 1,
[Display(Name = @"Gated Entry - Video")]
GatedEntryVideo = GatedEntry << 1,
[Display(Name = @"Closed-Circuit TV")]
CCTV = GatedEntryVideo << 1, ...
查找表有一個Value列,其值以指數方式增長,0,1,2,4,8,16,32,64,128,256,512
最后,UI具有多選輸入,其中值與查找表的編號順序相同。 有一個衛生功能作用於這樣的價值(knockout.js)
self.Value = ko.computed({
read: function () {
var value = 0;
$.each(self.Selected(), function (idxitem, item) {
value |= item;
});
return value;
},
write: function (value) {
$.each(self.Available(), function (idxitem, item) {
if ((value & item.Value) > 0) {
item.IsSelected(true);
}
});
self.Normalize(value);
},
owner: self
});
我不明白這應該如何接受多個選擇。
這聽起來像它的實施標志 。 這允許您具有可以表示多個不同值的單個枚舉值
這是一個簡短的例子
class Program
{
static void Main(string[] args)
{
FlaggedEnum fruitbowl = FlaggedEnum.Apples | FlaggedEnum.Oranges | FlaggedEnum.Pears;
Console.WriteLine(fruitbowl);
Console.ReadLine();
}
}
[Flags]
enum FlaggedEnum
{
None = 0,
Apples = 1,
Pears = 2,
Oranges = 4,
Pineapples = 8
}
當你運行它時,你得到輸出“蘋果,橘子,梨”。 其整數值為7(4 + 2 + 1)。
2的冪的原因是由於它們的二進制等價,1 = 1,2 = 10 4 = 100,8 = 1000 ......所以這給出了值111。
我希望這至少讓你走上正確的道路。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.