Grz*_*rzM 3 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();
}
}
Run Code Online (Sandbox Code Playgroud)
如果您使用SharpLab,您可以在降低的代码中看到该属性确实已从属性中删除,而是应用于返回参数:
public string Bar
{
[CompilerGenerated]
[return: NotNull] // Note the "return" target
get
{
return <Bar>k__BackingField;
}
//snip
}
Run Code Online (Sandbox Code Playgroud)
所以如果你想获得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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
160 次 |
| 最近记录: |