确定在C#中设置了哪个'oneof' proto3字段

5
对于以下协议缓冲区消息(proto3),我如何确定设置了哪种类型?似乎没有像生成的C++版本那样的“has_reply”方法。
message Event {
  oneof type {
    Connection connection = 1;
    StatusReply reply = 2;
    Error error = 3;
    End end = 4;
    Empty empty = 5;
  };
}
1个回答

8

https://developers.google.com/protocol-buffers/docs/reference/csharp-generated#oneof建议使用TypeOneofCase来确定哪个字段被设置:

Oneof Fields

Each field within a oneof has a separate property, like a regular singular field. However, the compiler also generates an additional property to determine which field in the enum has been set, along with an enum and a method to clear the oneof. For example, for this oneof field definition

oneof avatar {
  string image_url = 1;
  bytes image_data = 2;
}

The compiler will generate these public members:

enum AvatarOneofCase
{
  None = 0,
  ImageUrl = 1,
  ImageData = 2
}

public AvatarOneofCase AvatarCase { get; }
public void ClearAvatar();
public string ImageUrl { get; set; }
public ByteString ImageData { get; set; }

If a property is the current oneof "case", fetching that property will return the value set for that property. Otherwise, fetching the property will return the default value for the property's type - only one member of a oneof can be set at a time.

Setting any constituent property of the oneof will change the reported "case" of the oneof. As with a regular singular field, you cannot set a oneof field with a string or bytes type to a null value. Setting a message-type field to null is equivalent to calling the oneof-specific Clear method.


1
否则,获取属性将返回属性类型的默认值 - 一个oneof成员一次只能设置一个。这太糟糕了!默认值和未设置不是同一回事!这基本上使C#实现的oneof无用。 - Isen Ng
1
@IsenGrim 不过,你有什么其他的替代方案吗(即,你会用其他方式构建它)?ImageUrl是一个string - 因此,它基本上需要返回实际上是string的东西 - 它不能返回其他东西。这里的关键是在决定读取ImageUrl还是ImageData之前先阅读AvatarCase属性。 - mjwills

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接