c# - 通过反射检查时缺少 NotNullAttribute

标签 c# reflection attributes nullable-reference-types

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

有谁知道为什么会这样?在互联网/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您可以在降低的代码中看到该属性确实已从属性中删除,而是应用于返回参数:

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

关于c# - 通过反射检查时缺少 NotNullAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71144165/

相关文章:

c# - 如何使用Bass库将音频转换为另一种格式(使用C#)

c# - OnMethodBoundaryAspect 是如何工作的?

c# - 是否有可能知道 wpf 中的样式中有哪些 setter 可用?

c# - 如何使用 AVCaptureVideoDataOutput 避免 AVCaptureSession 中的丢帧

c# - 复制大文件时Forms application "Not Responding"?

objective-c - 使用反射的属性类型或类

c# - WCF 获取入口程序集

c# - 如何检查该类型是从某些接口(interface)继承的 C#

python - Python 中的类继承

ruby-on-rails - Ruby on Rails - 我可以在调用之前修改属性的值吗?