Search code examples
c#.netreflection.net-8.0native-aot

Generic parameter does not have matching annotations in .NET 8 AOT


I have a helper method that returns a list of public static readonly fields of a type:

public static ReadOnlyCollection<T> GetFields<T>()
    where T : class
{
    return typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static)
        .Where(x => x.IsInitOnly && x.FieldType == typeof(T))
        .Select(x => (T)x.GetValue(null))
        .ToList().AsReadOnly();
}

When I convert my project to .NET 8 AOT, I'm getting the following error:

error IL2090: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicFields' in call to 'System.Type.GetFields(BindingFlags)'. The generic parameter 'T' of 'path\to\helper\GetFields()' does not have matching annotations. The source value must declare at least the same requirements as those declared on the target location it is assigned to.

How can I fix this error? The helper method is called by unit tests only to ensure constant fields in specific classes are unique and follow certain syntax conventions.


Solution

  • Mark the generic parameter with DynamicallyAccessedMembersAttribute (passing corresponding value to memberTypes parameter):

    public static ReadOnlyCollection<T> GetFields<
        [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)]
        T>()
        where T : class
    {
        // ...
    }