如果您还想保留列表或集合本身的内容,您应该考虑公开一个属性以返回列表。它必须被包装以防止序列化时出现循环问题:
注意:此解决方案同时支持序列化/反序列化。
[JsonObject]
public class FooCollection : List<int>
{
public string Bar { get; set; } = "Bar";
[JsonProperty]
ICollection<int> Items => new _<int>(this);
}
internal class _<T> : ICollection<T>
{
public _(ICollection<T> collection) => inner = collection;
private ICollection<T> inner;
int ICollection<T>.Count => inner.Count;
bool ICollection<T>.IsReadOnly => inner.IsReadOnly;
void ICollection<T>.Add(T item) => inner.Add(item);
void ICollection<T>.Clear() => inner.Clear();
bool ICollection<T>.Contains(T item) => inner.Contains(item);
void ICollection<T>.CopyTo(T[] array, int arrayIndex) => inner.CopyTo(array, arrayIndex);
IEnumerator<T> IEnumerable<T>.GetEnumerator() => inner.GetEnumerator();
bool ICollection<T>.Remove(T item) => inner.Remove(item);
IEnumerator IEnumerable.GetEnumerator() => inner.GetEnumerator();
}
new FooCollection { 1, 2, 3, 4, 4 }
=>
{
"bar": "Bar",
"items": [
1,
2,
3
],
"capacity": 4,
"count": 3
}
new FooCollection { 1, 2, 3 }.ToArray()
=>new []{1, 2, 3}.ToArray()