TypeScript 中的枚举标志是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39359740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What are enum Flags in TypeScript?
提问by Jaime Rios
I'm learning TypeScript using this ebookas a reference. I've checked the TypeScript Official Documentationbut I don't find information about enum flags.
我正在使用这本电子书作为参考来学习 TypeScript 。我检查了TypeScript 官方文档,但没有找到有关枚举标志的信息。
回答by David Sherret
They're a way to efficiently store and represent a collection of boolean values.
它们是一种有效存储和表示布尔值集合的方法。
For example, taking this flags enum:
例如,以这个标志枚举:
enum Traits {
None = 0,
Friendly = 1 << 0, // 0001 -- the bitshift is unnecessary, but done for consistency
Mean = 1 << 1, // 0010
Funny = 1 << 2, // 0100
Boring = 1 << 3, // 1000
All = ~(~0 << 4) // 1111
}
Instead of only being able to represent a single value like so:
而不是只能像这样表示单个值:
let traits = Traits.Mean;
We can represent multiple values in a single variable:
我们可以在一个变量中表示多个值:
let traits = Traits.Mean | Traits.Funny; // (0010 | 0100) === 0110
Then test for them individually:
然后分别测试它们:
if ((traits & Traits.Mean) === Traits.Mean) {
console.log(":(");
}
回答by Patrick Desjardins
The official documentation has this example that I will add some details that are crucial to use enum and flags.
官方文档有这个例子,我将添加一些对使用枚举和标志至关重要的细节。
enum FileAccess {
None,
Read = 1 << 1,
Write = 1 << 2,
}
In TypeScript, you can assign a value directly with =
在 TypeScript 中,您可以直接使用 =
let x:FileAccess = FileAccess.Read;
But this might override previous values. To get around that you can use |=
to append a flag.
但这可能会覆盖以前的值。为了解决这个问题,您可以使用|=
附加标志。
x |= FileAccess.Write;
At this point, the variable x
is Read and Write. You can remove a value by using the ampersand and tilde:
此时,变量x
为 Read 和 Write。您可以使用与号和波浪号来删除值:
x &= ~FileAccess.Read;
Finally, you can compare to see if one of the value is set to the variable. The accepted answer is not right. It should not just use the ampersand symbol but also check with ===
to the desired value. The reason is the ampersand returns a number, not a boolean.
最后,您可以进行比较以查看是否将其中一个值设置为变量。接受的答案是不正确的。它不应该只使用与符号,还应该检查===
所需的值。原因是&符号返回一个数字,而不是一个布尔值。
console.log(FileAccess.Write === (x & FileAccess.Write)); // Return true
console.log(FileAccess.Read === (x & FileAccess.Read)); // Return false
回答by snehal badhe
enum Info{
None = 0,
glass= 1 << 0, // 0001 -- the bitshift is unnecessary, but done for consistency
plastic= 1 << 1, // 0010
}
回答by basarat
Flags allow you to check if a certain condition from a set of conditions is true. This is a common programming pattern in various other programming languages e.g. here is an example about C# : Using Bitwise operators on flags
标志允许您检查一组条件中的某个条件是否为真。这是各种其他编程语言中的常见编程模式,例如,这里有一个关于 C# 的示例:在标志上使用位运算符