简体   繁体   English

c# 在方法调用后告诉 Visual Studio 属性不是 null

[英]c# tell Visual Studio that property is not null after method call

How can I tell Visual Studio IntelliSense that property of property is not null after calling its method调用方法后如何告诉 Visual Studio IntelliSense 属性的属性不是 null

Inner class:内 class:

class Inner
{
    int? Property { get; set; }

    [MemberNotNull(nameof(Property))]
    void Initialize
    {
        Property = 42;
    }
}

Caller class:来电者 class:

class Caller
{
    // We know here that constructor is always called before other methods
    public Caller()
    {
        InnerObj = new Inner();

        // We know here that InnerObj.Property is always not null
        InnerObj.Initialize();
    }

    public Inner InnerObj { get; }

    public void MethodWithNullWarning()
    {
        // Null Warning
        InnerObj.Property.ToString();
    }
}

You can use the null-forgiving operator .您可以使用null-forgiving operator

InnerObj!.Property.ToString();

Quoted from docs:引用自文档:

Available in C# 8.0 and later, the unary postfix, operator is the null-forgiving, or null-suppression.在 C# 8.0 及更高版本中可用,一元后缀运算符是 null-forgiving 或 null-suppression。 operator, In an enabled nullable annotation context: you use the null-forgiving operator to declare that expression x of a reference type isn't null.运算符,在启用的可空注释上下文中:您使用容错运算符来声明引用类型的表达式 x 不是 null。 x.. The unary prefix ! x.. 一元前缀 ! operator is the logical negation operator.运算符是逻辑否定运算符。

Assigning the property in the constructor doesn't guarantee it will not be null.在构造函数中分配属性并不能保证它不会是 null。

Let's add the following method:让我们添加以下方法:

public void MakeItNull() { InnerObj.Property = null; }

Then:然后:

Caller caller = new ();

caller.MakeItNull();
caller.MethodWithNullWarning();

Boom!繁荣!


Solutions解决方案

Here are some options.这里有一些选项。

1. ! 1.!

! (null-forgiving) operator (C# reference) (null-forgiving) 运算符(C# 参考)

InnerObj.Property!.ToString();

Please note that this doesn't protect from a null reference exception if the value is actually null.请注意,如果值实际上是 null,则这不能防止 null 引用异常。

2. Have a constructor 2.有一个构造函数

class Inner
{
    public string Property { get; set; } // string, not string!

    public Inner() {
        Property = "42";
    }
}

3. Use a different property for external access. 3. 使用不同的属性进行外部访问。

class Inner
{
    private string? RealProperty { get; set; }


    public string Property => RealProperty!;

    public void Initialize() {
        RealProperty = "42";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM