I'm taking over a C# project and I have come across a concept that I'm unfamiliar with.
The project is using EF to create look-up tables from enums. The UI is accepting a multi-select input but the receiving model accepts a enum type, not a list/array or something else that would suggest plural.
The enum seems to have some recursive relationship
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, ...
the look-up table has a Value column that with value that grow exponentially, 0,1,2,4,8,16,32,64,128,256,512
and finally the UI has a multi-select input where the value is the same number sequence as the look-up table. There is a sanitation function acting on the value like this (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
});
I do not understand how this is supposed to accept plural selections.
It sounds like its implementing flags . This allows you to have a single Enum value that can represent several different values
Here's a short example
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
}
When you run this you get the output "Apples, Oranges, Pears". Its integer value would be 7 (4 + 2 + 1).
The reason for powers of two is due to their binary equivalents, 1 = 1, 2 = 10 4 = 100, 8 = 1000... So this gives 7 the value of 111.
I hope this puts you on the right path at least.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.