Serialization Protobuf.Net:序列化列表<;Uri>;抛出;无法强制转换类型为';System.Uri';输入';System.String'&引用;

Serialization Protobuf.Net:序列化列表<;Uri>;抛出;无法强制转换类型为';System.Uri';输入';System.String'&引用;,serialization,protobuf-net,Serialization,Protobuf Net,标题说明了一切,Protobuf.net正确地序列化了Uri,但不会序列化List [协议] 类SingleUri { [原成员(1)] 公共Uri{get;set;} } [原始合同] 类多URI { [原成员(1)] 公共列表URI{get;set;} } 静态void Main(字符串[]参数) { var single=new SingleUri{Uri=new Uri(“http://www.google.com") }; 使用(var file=file.Create(“single

标题说明了一切,Protobuf.net正确地序列化了
Uri
,但不会序列化
List

[协议]
类SingleUri
{
[原成员(1)]
公共Uri{get;set;}
}
[原始合同]
类多URI
{
[原成员(1)]
公共列表URI{get;set;}
}
静态void Main(字符串[]参数)
{
var single=new SingleUri{Uri=new Uri(“http://www.google.com") };
使用(var file=file.Create(“single.bin”))
//工作是一种享受
序列化器。序列化(文件,单个);
var multi=new MultiUri{Uris=new List{single.Uri};
使用(var file=file.Create(“multi.bin”))
//与System.InvalidCastException一起失败:无法强制转换对象
//将“System.Uri”类型更改为“System.String”。
序列化(文件,多个);
}
在撰写本文时,我正在针对最新的NuGet软件包运行此程序

有人能告诉我我错过了什么吗?有解决办法吗


谢谢。

很有趣。我没有意识到这一点——听起来像是一只虫子。我去看看。一个解决方法是:在DTO中存储字符串,而不是Uri对象:)谢谢Marc,我觉得这不是我正在做的事情,Pb.net是一个很好的工具,谢谢你滚动它,很抱歉给你的室友带来麻烦。看起来像这里描述的问题:像@Marc建议的那样解决它,尽管
System.Uri
在强制使用有效的Uri方面很方便,而且当
System.String
用于像Uri这样的属性时,甚至FxCop也会唠叨不休,因此需要一个解决方案。
[ProtoContract]
class SingleUri
{
    [ProtoMember(1)]
    public Uri Uri { get; set; }
}
[ProtoContract]
class MultiUri
{
    [ProtoMember(1)]
    public List<Uri> Uris { get; set; }
}

static void Main(string[] args)
{
    var single = new SingleUri { Uri = new Uri("http://www.google.com") };
    using (var file = File.Create("single.bin"))
        // Works a treat
        Serializer.Serialize(file, single);

    var multi = new MultiUri { Uris = new List<Uri> { single.Uri } };
    using (var file = File.Create("multi.bin"))
        // fails with System.InvalidCastException: Unable to cast object 
        //of type 'System.Uri' to type 'System.String'.
        Serializer.Serialize(file, multi); 
}