gpt4 book ai didi

c# - 如何初始化一个对象?

转载 作者:太空宇宙 更新时间:2023-11-03 17:16:23 25 4
gpt4 key购买 nike

我有这样一个类,

public class person
{
name Name {set; get;}
string Address {set; get;}
}

public class name
{
string First {set; get;}
string Last {set; get;}
}

现在,当我创建对象并尝试设置名字或姓氏时,出现错误。 “对象引用未设置到对象的实例。”

person Person = new person();
Person.Name.First = "John";
Person.Name.Last ="Smith";

我做错了什么?

最佳答案

您也需要初始化名称类实例

person Person = new person();
Person.Name = new name();
Person.Name.First = "A";

如果你愿意,你也可以在 person 的构造函数中这样做

public class person
{
public name Name { set; get; }
string Address { set; get; }

public person()
{
Name = new name();
}
}

甚至尝试

person Person = new person { Name = new name { First = "A", Last = "B" } };

关于c# - 如何初始化一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2579623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com