Reflection with InlineArrayAttribute?
If I have an
object o
that I know is a struct with InlineArrayAttribute
, how would I go about getting/setting each of the items?
I can get the length with o.GetType().GetCustomAttribute<InlineArrayAttribute>()?.Length
And I can get its field with o.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Single()
But using fieldInfo.GetValue/fieldInfo.SetValue
seems to only get/set the item at index 0 in the array.12 Replies
(are you passing index in SetValue?)
(also if you know the type cannot you cast it?)
If I could cast it I wouldn't be using reflection in the first place.
maybe there could be known or easier cases
It's a utility method that walks the object graph using reflection
When I add inline arrays it doesn't walk each item in it
What is preventing you from casting, out of curiosity?
I think the easiest option here would be to make sure that every type you're attempting to handle can be described by a common interface. Then you should be able to cast it to that interface and get the info you need from that. Is there anything preventing you from using an interface here?
I use the same utility method to walk
List<T>
and other sorts of BCL types. I can't add an interface there.this could work
at least it's work a try
No that's a cast exception
Not sure if this helps, but here you can see if
o
is a kind of List<T>
when you don't know what T
is
if (o.GetType() == typeof(List<>).MakeGeneric(o.GetType().GetGenericArguments()[0])) { ... }
This will throw an out of bounds exception if the type isn't generic, so do keep that in mindmmm well this is wrong
this shouldn't get the field, since the declaring type should already be an array
yeah i don't exactly know what type an InlineArray is under the hood, but it's not the usual array
maybe you can ask in #allow-unsafe-blocks
you basically can't
accessing the elements of an InlineArray is done through unsafe code that is very hard to do with reflection
with a pinned GCHandle you can probably just barely get away with something, but that means it won't work for any InlineArrays of reference types
I remain undeterred
After looking at how the compiler synthesizes converting inline arrays to span, this is what I'm thinking: