【发布时间】:2021-05-24 03:18:51
【问题描述】:
我正在使用 protobuf-net 包版本 3.0.101。
以下代码在执行typeModel.Serialize(ms, value) 时会产生运行时异常。例外是:
GenericArguments[0], 'UserQuery+Option`1[System.Int32]', on 'ProtoBuf.Serializers.RepeatedSerializer`2[TCollection,T] CreateEnumerable[TCollection,T]()' violates the constraint of type 'TCollection'.
void Main()
{
var typeModel = RuntimeTypeModel.Create();
typeModel.SetSurrogate<Option<int>, OptionSurrogate<int>>();
//typeModel[typeof(Option<int>)].IgnoreListHandling = true; // This doesn't help.
var value = new Option<int>(true, 5);
var ms = new MemoryStream();
typeModel.Serialize(ms, value);
}
struct Option<T> : IEnumerable<T>
{
public Option(bool hasValue, T value)
{
HasValue = hasValue;
Value = value;
}
public readonly bool HasValue;
public readonly T Value;
public IEnumerator<T> GetEnumerator()
{
if (HasValue) {
yield return Value;
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
[ProtoContract]
struct OptionSurrogate<T>
{
public OptionSurrogate(Option<T> thing) {
HasValue = thing.HasValue;
Value = thing.Value;
}
[ProtoMember(1)]
public readonly bool HasValue;
[ProtoMember(2)]
public readonly T Value;
public static implicit operator Option<T>(OptionSurrogate<T> surrogate) => new Option<T>(surrogate.HasValue, surrogate.Value);
public static implicit operator OptionSurrogate<T>(Option<T> value) => new OptionSurrogate<T>(value);
}
有两件事可以解决这个问题:
- 将
struct Option<T>更改为class Option<T> - 从
struct Option<T>中删除IEnumerable<T>
但是,这些都不可能,因为我要序列化的 struct 位于第 3 方库中。
这是protobuf-net 中的错误还是有解决方法?
【问题讨论】:
-
这看起来可能是相关的,但我尝试挑选它并没有帮助:github.com/protobuf-net/protobuf-net/pull/755
标签: c# protobuf-net