如何从财产中获得枚举值 [英] How to get enum value from property
本文介绍了如何从财产中获得枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个值为 VALID
和 INVALID
的枚举,它们具有与之关联的布尔属性.我想根据我提供的布尔值获取枚举值.
I have an enum with values VALID
and INVALID
, which have a boolean property associated with them. I would like to get the enum value based on a boolean value I provide.
如果它是 true
,我应该得到 VALID
,如果它是 false
,我应该得到 INVALID
.我想根据成员变量的值,在如下所示的getter方法中这样做
If it is true
I should get VALID
, if it is false
I should get INVALID
. I would like to do so in a getter method like the below, based on the value of the member variable
public boolean getCardValidityStatus() {
return CardValidationStatus status = CardValidationStatus(this.mCardValidityStatus));
}
我的代码:
private enum CardValidationStatus {
VALID(true),
INVALID(false);
private boolean isValid;
CardValidationStatus(boolean isValid) {
this.isValid = isValid;
}
public boolean getValidityStatus() {
return this.isValid;
}
}
推荐答案
您可以使用枚举本身中的静态查找方法来实现这一目标:
You're able to achieve that using a static lookup method in the enum itself:
private enum CardValidationStatus {
VALID(true),
INVALID(false);
//...
public static CardValidationStatus forBoolean(boolean status) {
//this is simplistic given that it's a boolean-based lookup
//but it can get complex, such as using a loop...
return status ? VALID : INVALID;
}
}
可以使用以下方法检索适当的状态:
And the appropriate status can be retrieved using:
public CardValidationStatus getCardValidityStatus() {
return CardValidationStatus.forBoolean(this.mCardValidityStatus));
}
这篇关于如何从财产中获得枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文