英文:
How do I tell the compiler that a property is not null when a certain method has been executed?
问题
在我的基类中考虑以下代码:
public MyClass? Input { get; set; }
protected virtual void DoSomething()
{
Input = new();
}
现在我想要重写这个方法并修改 Input 属性的一些属性:
protected override void DoSomething()
{
base.DoSomething();
Input.Name = "Test";
}
现在我收到了警告:
CS8602 - Dereference of a possibly null reference.
我知道我可以这样说它不能为 null:
Input!.Name = "Test";
但我不想每次都这样做。有没有一种更好的方法告诉编译器,在函数的基类已经执行时,Input 不会为 null?
英文:
Consider this code within my base class
public MyClass? Input { get; set; }
protected virtual void DoSomething()
{
Input = new();
}
Now I want to override the method and modify some properties on my Input property.
protected override void DoSomething()
{
base.DoSomething();
Input.Name = "Test";
}
Now I get the warning
CS8602 - Dereference of a possibly null reference.
I know I can say that it cannot be null be doing it like this:
Input!.Name = "Test";
But I don't want to do it everytime. Is there a better way to tell the compiler that Input is not null, when the base of the function has already been executed?
答案1
得分: 4
你想要 [MemberNotNull(nameof(Input))]
。
这告诉编译器,在装饰的方法执行后,指定的属性将是非空的。
[MemberNotNull(nameof(Input))]
protected virtual void DoSomething()
{
Input = new();
}
<details>
<summary>英文:</summary>
You want [`[MemberNotNull(nameof(Input))]`](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/attributes/nullable-analysis#helper-methods-membernotnull-and-membernotnullwhen).
This tells the compiler that the named property will be non-null after the decorated method has executed.
[MemberNotNull(nameof(Input))]
protected virtual void DoSomething()
{
Input = new();
}
[SharpLab](https://sharplab.io/#v2:C4LgTgrgdgNAJiA1AHwAIAYAEqCMA6AEQEsBDAcygHsBnYIgY2rwGFK4BTAQShIBsBPakWoBuALAAoSagDM2AEyYAsv2a8S1apIDekzPuxzcWAHIkAtu0zbMZdsBGZq9xwF9MAXkxQIvXgEJxCVdJaSNFACENdh09A1llVXVNAH5MAEkoAAcIYGtbFydCkIkDTDj9AG0ldnMAI3YwE0pgE19eAAoeS0oAMw7MnOAASmGAXQrMLLAW9npgdjhMADciMGAIPmwAFkwCSgBlSktgAAsiKDIO4cndUrKDQdzPb3YAd2ugspKSsIU9xpEZaLTAgTBRZyxe76aazeYgyjAsBgIgcHZ7Q7HeznS7XW6TMp1aKETEnHFXYZBAmPbK5PBmSwvABEABV2LQmV8DD9JEA==)
</details>
# 答案2
**得分**: 4
你可以使用[`MemberNotNull`][1]来实现这一点。
```csharp
[MemberNotNull(nameof(Input))]
protected virtual void DoSomething()
{
Input = new();
}
英文:
You could use the MemberNotNull
for that.
[MemberNotNull(nameof(Input)]
protected virtual void DoSomething()
{
Input = new();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论