Lo que intentamos hacer es enumerar todas las propiedades de la clase con el atributo NotNull. El de .NET, no el de JetBrains. Desafortunadamente, parece que NotNullAttribute se eliminó durante el proceso de compilación (o en alguna otra etapa) y no se puede observar en el tiempo de ejecución.
¿Alguien sabe por qué sucede? No puedo encontrar una explicación en Internet/MSDN.
Aquí hay una prueba que puede reproducirla fácilmente. Falla en la segunda afirmación.
public class Tests { public class Foo { [NotNull, Required] public string? Bar { get; set; } } [Test] public void GetAttributesTest() { var type = typeof(Foo); var property = type.GetProperties()[0]; Attribute.IsDefined(property, typeof(RequiredAttribute)).Should().BeTrue(); Attribute.IsDefined(property, typeof(NotNullAttribute)).Should().BeTrue(); } }
Si usa SharpLab , puede ver en el código reducido que el atributo se elimina de la propiedad y, en su lugar, se aplica al parámetro de retorno:
public string Bar { [CompilerGenerated] [return: NotNull] // Note the "return" target get { return <Bar>k__BackingField; } //snip }
Entonces, si desea obtener el atributo NotNull
, debe profundizar en la estructura. Por ejemplo:
var type = typeof(Foo); var property = type.GetProperties()[0]; var getMethod = property.GetGetMethod()!; var returnParameter = getMethod.ReturnParameter; Attribute.IsDefined(returnParameter, typeof(NotNullAttribute)).Should().BeTrue();