简体   繁体   English

C#do嵌套类需要实例化吗?

[英]C# do nested classes need to be instantiated?

In the following scenario: 在以下场景中:

public class outerclass
{
   public innerClass Ic
     {get;set}

   public class innerClass
   {

   }
}

Do you need to instantiate the inner class property before assigning values to it, like this? 在为其赋值之前,是否需要实例化内部类属性?

public class outerclass
{
   public outerclass()
     {
        this.Ic = new innerClass(); 
     }

   public innerClass Ic
     {get;set}

   public class innerClass
   {

   }
}

在声明的范围类中无关紧要 - 您应该始终以相同的方式使用类:在与特定类实例交互之前,您必须使用new运算符创建它。

Yes, unlike a base class you need to instantiate an inner class if you wish to use it. 是的,与基类不同,如果您希望使用它,则需要实例化内部类。

You can prove this to yourself quite easily by trying it: 你可以通过尝试来很容易地证明这一点:

public class OuterClass
{
    public InnerClass Ic { get; set; }

    public class InnerClass
    {
        public InnerClass()
        {
            Foo = 42;
        }

        public int Foo { get; set; }
    }
}

public class Program
{
    static void Main()
    {
        Console.WriteLine(new OuterClass().Ic.Foo);
    }
}

The above code throws a NullReferenceException because Ic has not been assigned. 上面的代码抛出NullReferenceException,因为尚未分配Ic

I would also advise you to follow the Microsoft naming convention and use pascal case for type names. 我还建议您遵循Microsoft命名约定并使用pascal case作为类型名称。

In this case the answer doesn't depend on the fact that the class is defined inside your outer class. 在这种情况下,答案不依赖于类在外部类中定义的事实。 Because you used the automatic getter/setter, a hidden backing field is used for the property Ic . 因为您使用了自动getter / setter,所以属性Ic使用隐藏的后备字段。 Like all fields of reference type, this field has a default value of null . 与所有引用类型字段一样,此字段的默认值为null Thus if you try to access the members of Ic without setting it to refer to some instance, you can expect a NullReferenceException . 因此,如果您尝试访问Ic的成员而不将其设置为引用某个实例,则可能会出现NullReferenceException

Everything I just said would still be true even if innerClass was defined somewhere else. 即使在其他地方定义了innerClass ,我刚才所说的一切仍然是真的。

No, the property is an instance of the class. 不,该属性是该类的实例。 The set would set a new instance anyway. 无论如何,该集合将设置一个新实例。 No need to construct one unless you want to make sure the get never returns null. 除非你想确保get永远不会返回null,否则不需要构造一个。

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

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