![](/img/trans.png)
[英]C# NET 3.5 : Property or indexer cannot be assigned to “--” it is read only
[英]Property or indexer 'property' cannot be assigned to -- it is read only in C#
我在 grpc C# 重复字段中遇到问题
在 grpc 原型中
message RpcResponseListAccountModel{
int32 status = 1;
repeated AccountItem Content = 2;
}
当响应是
IList<AccountItem> retVal = new List<AccountItem>();
return new RpcResponseListAccountModel
{
Status = 1,
Content = retVal // i can't set Content because say
}
因为说:属性或索引器属性不能分配给它在 C# 中只读
为什么?!!
它是一个只获取的集合属性——类似于(但不完全):
partial class RpcResponseListAccountModel
{
public List<AccountItem> Content { get; } = new List<AccountItem>();
// ...
}
而不是尝试分配一个新的集合:添加到现有的:
return new RpcResponseListAccountModel
{
Status = 1,
Content = { someItemToAdd }
};
这在语义上等同于:
var obj = new RpcResponseListAccountModel();
obj.Status = 1;
obj.Content.Add(someItemToAdd);
return obj;
如果您不想要任何项目(根据您的空列表示例),则根本不需要触摸Content
:
return new RpcResponseListAccountModel
{
Status = 1
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.