lundi 17 juillet 2023

How to determine whether a reference-based generic parameter is nullable [duplicate]

Generally, using C# reflection I've been able to get every detail that's ever been needed about a type. I've recently encountered a specific use-case that I have not been able to reflect: reference-based generic parameter nullability.

For example, given:

    public class ReflectMe
    {
        public List<long?> Ids0 { get; set; } = new List<long?>();

        [NullParam(true)]
        public List<String?> Names0 { get; set; } = new List<String?>();

        public List<long?>? Ids1 { get; set; } = new List<long?>();

        [NullParam(true)]
        [NullParam(true)]
        public List<List<String?>?>? Names1 { get; set; } = new List<List<string?>?>();
    }

The Ids0 and Ids1 can be reflected (via either Nullable.GetUnderlyingType or NullabilityInfoContext) since the inner long is a value-type. However, Names0 's String cannot be reflected, and Names1's inner List and String cannot be reflected.

The NullParam attribute was created as a work-around but is obviously not ideal.

Using C# v 11 (.NET 7.0) with Nullable enabled.

Any ideas about how this can be achieved?





Aucun commentaire:

Enregistrer un commentaire