我查看了这个答案,我处于不需要保持向后兼容性的情况,我必须有一个可以工作的解决方案,而无需使用 protobuf-net 所需的属性来装饰数十个类。所以我尝试使用RuntimeTypeModel.Default.InferTagFromNameDefault = true;
但我可能没有正确使用它,因为 Serializer.Serialize 调用仍然会引发异常,要求签订合同。这是我的快速测试,我做错了什么?
public enum CompanyTypes
{
None, Small, Big, Enterprise, Startup
}
public class BaseUser
{
public string SSN { get; set; }
}
public class User : BaseUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public DateTime BirthDate { get; set; }
public List<string> Friends { get; set; }
public Company Company { get; set; }
}
public class Company
{
public string Name { get; set; }
public string Address { get; set; }
public CompanyTypes Type { get; set; }
public List<Product> Products { get; set; }
}
public class Product
{
public string Name { get; set; }
public string Sku { get; set; }
}
[TestClass]
public class SerializationTest
{
[TestMethod]
public void SerializeDeserializeTest()
{
var user = new User
{
Age = 10,
BirthDate = DateTime.Now.AddYears(-10),
FirstName = "Test First",
LastName = "Test Last",
Friends = new List<string> { "Bob", "John" },
Company = new Company
{
Name = "Test Company",
Address = "Timbuktu",
Type = CompanyTypes.Startup,
Products = new List<Product>
{
new Product{Name="Nerf Rocket", Sku="12324AC"},
new Product{Name="Nerf Dart", Sku="DHSN123"}
}
}
};
RuntimeTypeModel.Default.InferTagFromNameDefault = true;
using (var memoryStream = new MemoryStream())
{
Serializer.Serialize(memoryStream, user);
var serialized = Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
}
}
}