-
I'm trying to access the internal using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
var list = new List<string>() { "ahoyhoy" };
//reflection works
var internalItemsOld = (string[])list.GetType().GetField("_items", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(list)!;
Console.WriteLine(internalItemsOld.Length);
//UnsafeAccessor doesn't appear to work?
var internalItemsNew = GetListItems(list);
Console.WriteLine(internalItemsNew.Length);
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_items")]
extern static ref T[] GetListItems<T>(List<T> list); The reflection-based way works fine but the
UnsafeAccessor-with-generics had a bumpy start, but since #89439 (.NET 9) it should be working, no? Am I doing something wrong? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
The answer is the same as in #110054 (comment) In your case, using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
var list = new List<string>() { "ahoyhoy" };
var internalItemsNew = Accessors<string>.GetListItems(list);
Console.WriteLine(internalItemsNew.Length);
class Accessors<T>
{
[UnsafeAccessor(UnsafeAccessorKind.Field, Name = "_items")]
public extern static ref T[] GetListItems(List<T> list);
} |
Beta Was this translation helpful? Give feedback.
-
.... Do you really need the underlying array? There's also CollectionsMarshal.AsSpan, which would give you a |
Beta Was this translation helpful? Give feedback.
The answer is the same as in #110054 (comment)
In your case,
T
should be type parameter and not method parameter, as inList<T>
T
- is a type parameter.Following code works as expected: