我在 iOS 上作業,現在我必須處理顫振。
案例是當我使用 swift 時,我能夠根據不同的列舉案例訪問具有不同型別別的規則變數。
示例代碼如下:
enum SensorTypeRule{
case Lamp(rule:LampRule)
case Counter(rule:CounterRule)
}
struct LampRule{
let ruleTriggerColor: LampColor
let ruleSustainedMilliseconds: UInt32
}
struct CounterRule{
let ruleLimit: UInt32
}
并且可以像下面這樣訪問:
let sensorTypeRule:SensorTypeRule = someSensorTypeRuleInstance
switch sensorTypeRule{
case .Lamp(let rule):
print("\(rule. ruleSustainedMilliseconds)")
case .Counter(let rule):
print("\(rule.ruleLimit)")
}
飛鏢中有等效的方法嗎?
uj5u.com熱心網友回復:
Dart 沒有密封類的概念,但是你可以這樣做:
// Create an abstract class representing an enum
// This enum can be instantiated in two ways: either
// calling SensorTypeRule.lamp or SensorTypeRule.counter
abstract class SensorTypeRule {
const factory SensorTypeRule.lamp(LampRule rule) = Lamp._;
const factory SensorTypeRule.counter(CounterRule rule) = Counter._;
const SensorTypeRule();
}
// Create the rules inside each respective class
// Using _ as constructor name disallows the user
// to instantiate it directly -> Lamp(...)
// Instead, it must use the base class -> SensorTypeRule.lamp(...)
class Lamp extends SensorTypeRule {
final LampRule rule;
const Lamp._(this.rule);
}
class Counter extends SensorTypeRule {
final CounterRule rule;
const Counter._(this.rule);
}
// Define the rules
class LampRule {
final LampColor ruleTriggerColor;
final int ruleSustainedMilliseconds;
const LampRule({
required this.ruleTriggerColor,
required this.ruleSustainedMilliseconds,
});
}
class CounterRule {
final int ruleLimit;
const CounterRule({
required this.ruleLimit,
});
}
訪問它時,您可以這樣做:
final SensorTypeRule sensorTypeRule =
SensorTypeRule.counter(CounterRule(ruleLimit: 10));
if (sensorTypeRule is Lamp) {
print(sensorTypeRule.rule.ruleSustainedMilliseconds);
} else if (sensorTypeRule is Counter) {
print(sensorTypeRule.rule.ruleLimit);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/367324.html
標籤:镖
