I’m using protobuf-net v2 (r480) and I have a MetaType class where some members have been added via the Add() method. I’d like to enumerate them (get a collection of ValueMember objects), but it seems that despite having a by-index indexer, MetaType is not an IEnumerable.
I have found two unsatisfactory ways of enumerating the members: reflection over a private field of MetaType which will break when the internal implementation is changed, and brute force attack which is slow, wasteful and plain silly.
Reflection:
ValueMember[] fields = ((IEnumerable)typeof(MetaType)
.GetField("fields", BindingFlags.Instance | BindingFlags.NonPublic)
.GetValue(metaType)).OfType<ValueMember>().ToArray();
Brute force (LINQ is used for brevity, a for loop would probably be faster):
ValueMember[] fields = Enumerable.Range(0, int.MaxValue).Select(i => metaType[i])
.Where(m => m != null).ToArray();
Is there a better way?
Yes, it isn’t exposed. There is an internal.Fieldsproperty, but it would be worth adding a feature-request for exposing that on the public API.This is available from r581 onwards, by: