Background and motivation
MethodInfo.CreateDelegate is a really useful method to get a fast method invoke function for methods obtained by reflection. I miss the same method on FieldInfo. On FieldInfo, the delegate would have to return a ref to the field to be valid.
API Proposal
namespace System.Reflection;
// Current
// public abstract class MethodInfo : MethodBase
// {
// public virtual Delegate CreateDelegate(Type delegateType);
// public virtual Delegate CreateDelegate(Type delegateType, object? target);
// public T CreateDelegate<T>() where T : Delegate;
// public T CreateDelegate<T>(object? target) where T : Delegate;
// }
// Proposed
public abstract partial class FieldInfo : MemberInfo
{
public virtual Delegate CreateDelegate(Type delegateType);
public virtual Delegate CreateDelegate(Type delegateType, object? target);
public T CreateDelegate<T>() where T : Delegate;
public T CreateDelegate<T>(object? target) where T : Delegate;
}
API Usage
static class B
{
private string _foo;
}
static class C
{
private static FieldInfo _fieldInfo = typeof(B).GetField("_foo", BindingFlags.NonPublic | BindingFlags.Instance)!;
private static FooDelegate _fieldAccessor = _fieldInfo.CreateDelegate<FooDelegate>();
// Use _fieldAccessor repeatedly to access the field value (or set it to a new value)
// without the overhead of reflection after the initial delegate creation.
private delegate ref string FooDelegate(B b);
}
Alternative Designs
I don't know
Risks
I don't know any
Background and motivation
MethodInfo.CreateDelegateis a really useful method to get a fast method invoke function for methods obtained by reflection. I miss the same method on FieldInfo. On FieldInfo, the delegate would have to return a ref to the field to be valid.API Proposal
API Usage
Alternative Designs
I don't know
Risks
I don't know any