这是return type for getter problem when returning enum的延续。
当我使用枚举(enum.enum_value.name)时,我得到了一个错误,但是当我使用静态const字符串时,代码构建得很好。
我创建了一个enum.enum_value.name (SerialPortParity.none.name)变量,它正在创建一个String类型的变量。
final returnVal = SerialPortParity.none.name;我无法理解这种行为。
如果我得到错误The return type of getter 'parity' is 'String' which isn't a subtype of the type 'SerialPortParity' of its setter 'parity'.,那么为什么当我返回static const String时没有得到相同的错误
运行代码:
static const String parityNone = 'None';
static const String parityEven = 'Even';
static const String parityOdd = 'Odd';
static const String parityMark = 'Mark';
static const String paritySpace = 'Space';
int _parity = UsbPort.PARITY_NONE;
String get parity {
switch (_parity) {
case UsbPort.PARITY_NONE:
return SerialPort.parityNone;
case UsbPort.PARITY_EVEN:
return SerialPort.parityEven;
case UsbPort.PARITY_ODD:
return SerialPort.parityOdd;
case UsbPort.PARITY_MARK:
return SerialPort.parityMark;
case UsbPort.PARITY_SPACE:
return SerialPort.paritySpace;
default:
return SerialPort.parityNone;
}
}
set parity(String parity) {
switch (parity) {
case SerialPort.parityNone:
_parity = UsbPort.PARITY_NONE;
break;
case SerialPort.parityEven:
_parity = UsbPort.PARITY_EVEN;
break;
case SerialPort.parityOdd:
_parity = UsbPort.PARITY_ODD;
break;
case SerialPort.parityMark:
_parity = UsbPort.PARITY_MARK;
break;
case SerialPort.paritySpace:
_parity = UsbPort.PARITY_SPACE;
break;
default:
//No Change
break;
}
}错误代码:
enum SerialPortParity {
none,
even,
odd,
mark,
space,
}
int _parity = UsbPort.PARITY_NONE;
String get parity {
switch (_parity) {
case UsbPort.PARITY_NONE:
return SerialPortParity.none.name;
case UsbPort.PARITY_EVEN:
return SerialPortParity.even.name;
case UsbPort.PARITY_ODD:
return SerialPortParity.odd.name;
case UsbPort.PARITY_MARK:
return SerialPortParity.mark.name;
case UsbPort.PARITY_SPACE:
return SerialPortParity.space.name;
default:
return SerialPortParity.none.name;
}
}
set parity(SerialPortParity parity) {
switch (parity) {
case SerialPortParity.none:
_parity = UsbPort.PARITY_NONE;
break;
case SerialPortParity.even:
_parity = UsbPort.PARITY_EVEN;
break;
case SerialPortParity.odd:
_parity = UsbPort.PARITY_ODD;
break;
case SerialPortParity.mark:
_parity = UsbPort.PARITY_MARK;
break;
case SerialPortParity.space:
_parity = UsbPort.PARITY_SPACE;
break;
default:
//No Change
break;
}
}错误:
The return type of getter 'parity' is 'String' which isn't a subtype of the type 'SerialPortParity' of its setter 'parity'.
Try changing the types so that they are compatible.发布于 2022-07-08 11:07:56
Setter和Getter必须使用相同的类型。
在你的例子中,要么是字符串,要么是Enum。
我们不能将这些因素混为一谈:
String get parity {} // STRING
set parity(SerialPortParity parity) {} // ENUM考虑下面的失能代码,它也对同一变量使用两种类型。
在Dart看来,当定义具有不匹配类型的Getter和Setter时,它就是这样的:
// Will not compile, as parity can be of one Type only.
class Abc {
String parity;
SerialPortParity parity;
}
var abc = Abc();
abc.partity = x;
var z = abc.partity;https://stackoverflow.com/questions/72910379
复制相似问题