在 C# 中,我可以做到这一点。
[Flags]
enum BeerProperty
{
Bold = 1,
Refreshing = 2
}
static void Taste(BeerProperty beer)
{
if (beer == (BeerProperty.Bold | BeerProperty.Refreshing))
{
Debug.WriteLine("I can't qutie put my finger on...");
}
}
static void Main(string[] args)
{
var tickBeer = BeerProperty.Bold | BeerProperty.Refreshing;
Taste(tickBeer);
}
在 Kotlin 中,我似乎不能“或”两个标志。 Kotlin 的方法是什么?使用枚举变量列表?
enum class BeerProperty(value:Int)
{
Bold(1),
Refreshing(2)
}
fun taste(beer:BeerProperty)
{
if(beer == (BeerProperty.Bold | BeerProperty.Refreshing))
{
print("I can't qutie put my finger on...");
}
}
fun main(args: Array<String>)
{
val tickBeer = BeerProperty.Bold | BeerProperty.Refreshing;
taste(tickBeer);
}
补充:感谢您的回答(由于时间限制,我还不能标记为答案)。我修改了下面的代码,实现了我想要的。
fun taste(beer: EnumSet<BeerProperty>)
{
if(beer.contains(BeerProperty.Bold) && beer.contains(BeerProperty.Refreshing))
{
print("I can't qutie put my finger on...");
}
}
fun main(args: Array<String>)
{
val tickBeer = EnumSet.of(BeerProperty.Bold, BeerProperty.Refreshing);
taste(tickBeer);
}
最佳答案
使用扩展函数
import java.util.*
enum class BeerProperty
{
BOLD,
REFRESHING,
STRONG;
infix fun and(other: BeerProperty) = BeerProperties.of(this, other)
}
typealias BeerProperties = EnumSet<BeerProperty>
infix fun BeerProperties.allOf(other: BeerProperties) = this.containsAll(other)
infix fun BeerProperties.and(other: BeerProperty) = BeerProperties.of(other, *this.toTypedArray())
fun taste(beer: BeerProperties) {
if(beer allOf (BeerProperty.BOLD and BeerProperty.REFRESHING and BeerProperty.STRONG)) {
print("I can't qutie put my finger on...")
}
}
fun main(args: Array<String>) {
val tickBeer = BeerProperty.BOLD and BeerProperty.REFRESHING and BeerProperty.STRONG
taste(tickBeer)
}
我使用扩展函数来允许使用 and 添加属性,并且 allof 来检查所有标志是否已设置。
关于kotlin - Kotlin 与 C# 中的标志枚举变量具有相似效果的方式是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49233991/