RicoSuter / NJsonSchema

JSON Schema reader, generator and validator for .NET
http://NJsonSchema.org
MIT License
1.38k stars 532 forks source link

Generic static field causes exception with `11.0.0` preview #1653

Closed ptasev closed 9 months ago

ptasev commented 9 months ago

I'm updating NSwag to 14.0.0 previews and I ran into a problem. Turns out it's with this library. I am getting the following exception message with version 11.0.0-preview006:

System.InvalidOperationException: Method may only be called on a Type for which Type.IsGenericParameter is true.

I did not have this problem with the same exact code in version 10.9.0 of the library. The problem goes away if the static field is removed. See code to reproduce below (tested with .NET 8.0):

using NJsonSchema.Generation;

JsonSchemaGenerator.FromType(typeof(Point2D<double>), new SystemTextJsonSchemaGeneratorSettings());

// This works with 10.9.0
// JsonSchemaGenerator g = new JsonSchemaGenerator(new JsonSchemaGeneratorSettings());
// g.Generate(typeof(Point2D<double>));

readonly struct Point2D<T>
    where T : unmanaged
{
    // THIS BREAKS NSWAG
    public static readonly Point2D<T> Zero = new();

    public T X { get; init; }

    public T Y { get; init; }

    public Point2D(T x, T y)
    {
        X = x;
        Y = y;
    }
}
ptasev commented 9 months ago

Looks like the issue is with Namotion.Reflection library. This error occurs on all versions >= 2.0.0. However, looks like this code path is only hit with NJsonSchema version 11.0.0.

using Namotion.Reflection;

var ct = typeof(Point2D<double>).ToContextualType();
// Getting fields fails
var fs = ct.Fields;
Pozix commented 9 months ago

I'm getting the same issue when generating an openApi spec with generic type via nswag

RicoSuter commented 9 months ago

Thanks for reporting, seems to be the same as this one here https://github.com/RicoSuter/NSwag/issues/4524#issuecomment-1833089046