简体   繁体   English

为类中的类的属性赋值

[英]Assign a value to a property of a class within a class

I have the following code 我有以下代码

class TopClass
{
    public string ClsProp1 { get; set; }
    public string ClsProp2 { get; set; }

    public SubClass ClsProp3 { get; set; }
}

class SubClass
{
    public string SCProp1 { get; set; }
    public string SCProp2 { get; set; }
}


class Program
{
    static void Main(string[] args)
    {

        Test.TopClass TCN = new Test.TopClass();

        TCN.ClsProp1 = "TCProp1--string value";
        TCN.ClsProp2 = "TCProp2--string value";
        TCN.ClsProp3.SCProp1 = "SCProp1--string value";
        TCN.ClsProp3.SCProp2 = "SCProp2--string value";

    }
}

I can't seem to figure out how to instantiate the TCN.ClsProp3.ScProp1 and TCN.ClsProp3.ScProp2 values. 我似乎无法弄清楚如何实例化TCN.ClsProp3.ScProp1和TCN.ClsProp3.ScProp2值。 I keep getting the "An unhandled exception of type 'System.NullReferenceException' occurred in Test.exe Additional information: Object reference not set to an instance of an object." 我不断收到“Test.exe中发生类型'System.NullReferenceException'的未处理异常附加信息:对象引用未设置为对象的实例。” error message. 错误信息。 Forgive my ignorance, I'm really trying to learn OOP from scratch. 原谅我的无知,我真的想从零开始学习OOP。

Thanks in advance 提前致谢

You need to initialize the ClsProp3 object before you can use it. 您需要先初始化ClsProp3对象,然后才能使用它。

TCN.ClsProp3 = new SubClass();

You could also initialize it in the TopClass constructor like this: 你也可以在TopClass构造函数中初始化它,如下所示:

class TopClass
{
    public TopClass()
    {
        ClsProp3 = new SubClass();
    }
    public string ClsProp1 { get; set; }
    public string ClsProp2 { get; set; }

    public SubClass ClsProp3 { get; set; }
}

When learning, it's better to pick a good domain. 学习时,最好选择一个好域名。 TopClass with ClsPropX do not make for a nice learning experience. TopClassClsPropX不使一个很好的学习经验。

As for your original question, launch the debugger and see what the ClsProp3 equals to. 至于你原来的问题,启动调试器,看看ClsProp3等于什么。 And bear in mind that it's impossible to assign anything to "nothingness", which is null in C# parlance. 请记住,不可能将任何内容分配给“虚无”,这在C#用语中是null

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

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