我有一个DataContracts的程序集,我需要为它生成.proto模式,以便能够与java系统交换数据.DataContracts代码可以更改,但我无法在其中添加[ProtoContract]和[ProtoMember]属性,因为它将导致protobuf-net程序集依赖性.我们在系统的C#部分中使用WCF,因此我们不希望在大多数不适用于Java系统的C#项目中依赖proto-buf程序集.
在GettingStarted部分的protobuf-net网站上,它说:
不喜欢属性?
在v2中,可以通过RuntimeTypeModel在运行时配置可以使用属性完成的所有操作.
但是我不知道如何在没有属性的情况下实际配置序列化,我还没有看到任何这样的例子.
我正在努力做到
[DataContract]
public class MyEntity
{
[DataMember(Order = 1)]
public String PropertyA { get; set; }
[DataMember(Order = 2)]
public int PropertyB { get; set; }
}
RuntimeTypeModel.Default.Add(typeof(MyEntity), false);
string proto = Serializer.GetProto<MyEntity>();
Run Code Online (Sandbox Code Playgroud)
并获得以下值作为 proto
package ProtobufTest;
message MyEntity {
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*ell 12
澄清:这个答案的大部分都与编辑前的问题有关,其中false传递给了RuntimeTypeModel.Add(...)
我namespace ProtobufTest用r2.0.0.640(当前的NuGet部署)使用了你的确切代码(我推断这是在,但其余的是从问题中复制/粘贴),我得到:
package ProtobufTest;
message MyEntity {
optional string PropertyA = 1;
optional int32 PropertyB = 2 [default = 0];
}
Run Code Online (Sandbox Code Playgroud)
此外,即使您删除该行,您也会得到完全相同的结果RuntimeTypeModel.Default.Add(...).
我不清楚为什么你会看到不同的东西 - 你能澄清一下:
[DataContract]/ [DataMember]属性是System.Runtime.Serialization.dll那些,或属于你自己(抱歉,如果这似乎是一个奇怪的问题)要完全回答这个问题:如果你没有任何属性(并且你拥有的属性也很好),你也可以这样做:
RuntimeTypeModel.Default.Add(typeof(MyEntity), false)
.Add(1, "PropertyA")
.Add(2, "PropertyB");
Run Code Online (Sandbox Code Playgroud)
它将配置PropertyA为键1和PropertyB键2.
| 归档时间: |
|
| 查看次数: |
5551 次 |
| 最近记录: |