我在 C 中跳過了這個列舉:
typedef enum
{
UndefinedGravity,
ForgetGravity = 0,
NorthWestGravity = 1,
NorthGravity = 2,
NorthEastGravity = 3,
WestGravity = 4,
CenterGravity = 5,
EastGravity = 6,
SouthWestGravity = 7,
SouthGravity = 8,
SouthEastGravity = 9
} GravityType;
我在 dart 中構建了它對應的列舉型別:
enum GravityType {
UndefinedGravity(0),
ForgetGravity(0),
NorthWestGravity(1),
NorthGravity(2),
NorthEastGravity(3),
WestGravity(4),
CenterGravity(5),
EastGravity(6),
SouthWestGravity(7),
SouthGravity(8),
SouthEastGravity(9);
final int value;
const GravityType(this.value);
static GravityType fromValue(int value) => GravityType.values.firstWhere((e) => e.value == value);
}
你可以看到它在 C 中具有相同的值,并且它們在 dart 中具有相同UndefinedGravity的ForgetGravity值。intint
現在考慮這個 C 函式:
int myFunc(...){
GravityType gt = ForgetGravity;
return gt;
}
如果我從 dart 呼叫此函式,它將回傳一個 dart int(在這種情況下為 0)。然后我可以呼叫GravityType.fromValue(returnedValue)但是我怎么知道它是否代表UndefinedGravity或者ForgetGravity我可以在 dart 中正確映射它?當前的實作fromValue是天真的并且將回傳 int 值的第一個匹配,所以我怎樣才能回傳與那個相同的列舉那是從C發送的?
uj5u.com熱心網友回復:
讓我們采用以下列舉:
// Broken example, firstType and secondType have the same value but aren't equal.
enum MyType {
firstType(0),
secondType(0),
thirdType(123);
final int value;
const MyType(this.value);
static MyType fromValue(int value) => MyType.values.firstWhere((e) => e.value == value);
}
稀疏、重疊列舉值的理想解決方案是將它們宣告為靜態常量:
enum MyType {
firstType(0),
thirdType(123);
// Make the overlapping value an alias of the first
static const secondType = firstType;
final int value;
const MyType(this.value);
static MyType fromValue(int value) => MyType.values.firstWhere((e) => e.value == value);
}
現在MyType.firstType == MyType.secondType回傳 true,secondType感覺與真正的列舉值相同,但實際上只是一個別名。
您可能會注意到的另一個問題是print(MyType.secondType)令人困惑的 prints MyType.firstType,這可以通過使用更具描述性的名稱創建一個新值來解決:
enum MyType {
firstOrSecondType(0),
thirdType(123);
// Both values are now an alias of firstOrSecondType
static const firstType = firstOrSecondType;
static const secondType = firstOrSecondType;
final int value;
const MyType(this.value);
static MyType fromValue(int value) => MyType.values.firstWhere((e) => e.value == value);
}
C 中的列舉不存盤它們的名稱,它們的字面值是整數,因此通過給 firstType 和 secondType 賦予相同的名稱不會丟失任何資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/529379.html
標籤:C镖达菲
上一篇:如何從Future回傳串列字串
