通过反射检查时缺少 NotNullAttribute

NotNullAttribute missing when checking by reflection

我们正在尝试做的是列出 class 的所有属性和 NotNull 属性。一个来自 .NET,而不是 JetBrains。不幸的是,看起来 NotNullAttribute 在编译过程中(或在其他某个阶段)被删除,并且无法在运行时观察到它。

有谁知道为什么会这样?找不到关于 internet/MSDN.

的解释

这是一个可以轻松重现的测试。它在第二个断言上失败。

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();
    }
}

如果您使用 SharpLab,您可以在降低的代码中看到该属性确实从 属性 中删除,而是应用于 return 参数:

public string Bar
{
    [CompilerGenerated]
    [return: NotNull] // Note the "return" target
    get
    {
        return <Bar>k__BackingField;
    }
    //snip
}

所以如果你想获得NotNull属性,你需要更深入地研究结构。例如:

var type = typeof(Foo);
var property = type.GetProperties()[0];
var getMethod = property.GetGetMethod()!;
var returnParameter = getMethod.ReturnParameter;

Attribute.IsDefined(returnParameter, typeof(NotNullAttribute)).Should().BeTrue();