【发布时间】:2016-12-11 17:37:04
【问题描述】:
我有一个输入登录名的注册表单。当我开始输入时,文本立即发送到检查登录是否可用的服务器。
答案必须是 0 或 1,对或错,取决于我是否会采取进一步行动。 但是 0/false 是默认字段值,它们不会被发送,字段只是保持为空,字段根本不存在(当且仅当字段不等于其默认值时,才会在线发送字段)。
我能用它做什么?我明确需要得到 0 或 1 的答案。当然,我使用的是字符串,但它有问题。
.proto
message InputChecking {
string login = 1;
int32 loginStatus = 2;
string mail = 3;
int32 mailStatus = 4;
}
message RegistrationRequest {
...
}
message WrapperMessage {
oneof msg {
InputChecking mes_inputChecking = 1;
RegistrationRequest mes_registrationRequest = 2;
}
}
.cpp
WrapperMessage wm; // protobuf message, is filled with data from the server
const google::protobuf::FieldDescriptor* inputCheckingField = wm.GetDescriptor()->FindFieldByName("mes_inputChecking");
if (wm.GetReflection()->HasField(wm, inputCheckingField)) // if inputCheckingField is
{
// It says that such a field is, when he receives a message from the server with loginStatus = 0, but there are no fields
const google::protobuf::FieldDescriptor* loginStatusField = wm.mes_inputchecking().GetDescriptor()->FindFieldByName("loginStatus");
if (wm.mes_inputchecking().GetReflection()->HasField(wm.mes_inputchecking(), loginStatusField))
{
// It is only called when the login is different from 0
Log("Login status = " + wm.mes_inputchecking().loginstatus());
}
}
【问题讨论】:
-
您并不清楚您想要的行为。如果您想要一个布尔值,则该值是否在线发送并不重要 - 只是接收到的值与“发送”的值相同。如果您想要三态,请使用枚举。这是proto2还是proto3?
-
@RichardHodges 我一般不会得到值 0,而且他没有字段(loginStatusField)。这是proto3。我会尝试通过枚举,
-
同样的问题,如果 ListFields 方法的值等于默认值 github.com/google/protobuf/issues/1772,则它不会返回字段
-
为什么要使用反射接口?只需测试消息中字段的值即可。
标签: c++ protocol-buffers