我正在尝试使用 protobuf-net 序列化通用类型,但 protobuf-net 说它无法序列化它。
As in:
RuntimeTypeModel.Default.CanSerialize(typeof(MyGenericClass<>))
返回 true 并且
RuntimeTypeModel.Default.CanSerialize(typeof(string))
也返回 true。但
RuntimeTypeModel.Default.CanSerialize(typeof(MyGenericClass<string>)) //--> applies to all types that would return true when directly serialized as shown above for the string type
返回假。我想我添加我的方式做错了MyGenericClass
到默认的运行时类型模型。因为像
RuntimeTypeModel.Default.CanSerialize(typeof(List<Document>))
返回真。
我当前添加通用类的代码:
var addedGenericType = RuntimeTypeModel.Default.Add(typeof(MyGenericClass<>), false);
addedGenericType.Add("Field1", "GenericField");
错误消息表明我尝试序列化的类型没有合同......这显然是不正确的。
这是一个演示我的问题并证明它应该有效的示例:
using System;
using ProtoBuf;
namespace TestApplication
{
[ProtoContract]
public class TestClass<T>
{
[ProtoMember(1, DynamicType = true)]
public T TestField { get; set; }
}
public class TestClass2<T>
{
public T TestField { get; set; }
}
public class Tester
{
public void Test()
{
DefineSecondClass();
bool testResult = ProtoBuf.Meta.RuntimeTypeModel.Default.CanSerialize(typeof(TestClass<string>));
bool testResult2 = ProtoBuf.Meta.RuntimeTypeModel.Default.CanSerialize(typeof(TestClass2<string>));
bool testResult3 = ProtoBuf.Meta.RuntimeTypeModel.Default.CanSerialize(typeof(TestClass2<>));
Console.WriteLine(testResult); // returns true
Console.WriteLine(testResult2); // returns false
Console.WriteLine(testResult3); // returns true
}
private void DefineSecondClass()
{
var type = ProtoBuf.Meta.RuntimeTypeModel.Default.Add(typeof(TestClass2<>), false);
type.AddField(1, "TestField");
type[1].DynamicType = true;
}
}
}
作为后续(并澄清我的评论)让我们采用以下代码:
使用系统;
使用 ProtoBuf;
namespace TestApplication
{
public class TestClass<T>
{
public T TestField { get; set; }
}
public class ComplexType
{
public string SomeFieldA{get; set;}
public int SomeFieldB{get; set;}
}
public class Tester
{
public void Test()
{
DefineComplexType();
// how to add the type TestClass<ComplexType> to the RuntimeTypeModel without calling
// DefineComplexType() again?
}
private void DefineComplexType()
{
var type = ProtoBuf.Meta.RuntimeTypeModel.Default.Add(typeof(ComplexType), false);
type.AddField(1, "SomeFieldA");
}
}
}