在grpc的原始文件中使用地图作为.net核心,以将字典作为请求参数发送,从而使其在自动生成的代码中成为私有字段(只读)。所以我无法分配字典来映射并在API请求中传递它。我如何使其可读写。?
Sample proto request:
service xyz{
rpc testTrans(TestRequest) returns (TestResponse);
}
message TestRequest {
map<string,string> props = 1;
}
所以自动生成的代码如下:
public const int PropsFieldNumber = 1;
private static readonly pbc::MapField<string, string>.Codec _map_Props_codec
= new pbc::MapField<string, string>.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForString(18), 10);
private readonly pbc::MapField<string, string> Props_ = new pbc::MapField<string, string>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::MapField<string, string> Props {
get { return Props_; }
}
所以现在当我尝试按如下所示在请求中分配属性时,它会引发错误: 属性或索引器TestRequest。无法将属性分配给它-只读。
public static void testTrans(Dictionary<string, string> test)
{
var res = client.InitTrans(new TestRequest
{
Props = test
});
}
答案 0 :(得分:0)
当您要直接声明和初始化值时,似乎已被阻止:
var res = client.InitTrans(new TestRequest
{
//Property could not be assigned to -- it is read only...error
Props = new Map<string,string>.Add("somekey", "somevalue");
// Alternatively the same problem will also occur when you do
// Props = new Map<string,string>.Add(SomeDict);
}
相反,应该变通办法是初始化变量,然后稍后(在整个消息对象初始化之后)将值添加到字典中。
var res = new TestRequest{};
//test is some dictionary
res.TestRequest.Props.Add(test);
//alternatively you can also add with (key, value)
res.TestRequest.Props.Add("someKey", "someValue);