C# 为什么不';当我编译typeModel时,有些内置类型不能工作吗?
当我编译类型模型时,字典停止工作C# 为什么不';当我编译typeModel时,有些内置类型不能工作吗?,c#,protobuf-net,C#,Protobuf Net,当我编译类型模型时,字典停止工作 [Test] public void TestCompileSerialization() { var data = new Dictionary<int, int>(); data[1] = 1; var typeModel = TypeModel.Create(); var compiledTypeModel = typeModel.Compile();
[Test]
public void TestCompileSerialization()
{
var data = new Dictionary<int, int>();
data[1] = 1;
var typeModel = TypeModel.Create();
var compiledTypeModel = typeModel.Compile();
using (var memory = new MemoryStream())
{
compiledTypeModel.Serialize(memory, data);
}
}
我是否需要添加我可能想要序列化到TypeModel的所有字典,或者有其他方法
顺便说一句,我不明白当我想预编译序列化程序时,为什么我必须公开所有内容?是的,当您创建自己的类型模型时,您需要提前告诉它要包含什么-否则它将不知道要支持什么。理想情况下,这包括所有要序列化为根类型的类型,因此:如果要序列化字典:告诉它。在内部,protobuf net v2实际上并没有特例词典——它将它们视为一个类似列表的类型序列(
KeyValuePair
),恰好看起来很像它可以猜测为“元组”的类型;protobuf net v3确实了解更多关于词典的信息,但是。。。你最好还是提前告诉我
顺便说一句,我不明白当我想预编译序列化程序时,为什么我必须公开所有内容
有两种类型的预编译;也许您实际上只是想要
CompileInPlace()
(而不是Compile()
),它保留了现有的RuntimeTypeModel
,但在封面下使用IL emit来创建轻量级垫片方法来完成工作;当使用这种方法时,可以绕过可访问性验证检查,允许我访问非公共内容;但是,当您使用Compile()
时,您正在实际程序集中创建实际类型(仅在内存中),并且当您这样做时:您无法绕过可访问性检查(以及一些其他验证检查);这意味着我要遵守与您在C#编译器中相同的规则:如果它不是公共的,我就不能碰它。谢谢您的精彩回答。现在我很好奇,在哪种情况下我可能会使用Compile?@kriper。现在,支持的场景确实不那么重要了;它与AOT场景的预编译有关,但是:还有其他问题,如果.NET编译器团队提供了基于“生成器”的方法,我希望将该方法替换为基于“生成器”的方法
Type is not expected, and no contract can be inferred: System.Collections.Generic.KeyValuePair`2[[System.Int32, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e],[System.Int32, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]