我有一个Car类,它具有Owner属性。所有者具有两个属性:名字和姓氏
在下面显示的单元测试中,我无法访问两个名称字段,
“名称“所有者”在当前上下文中不存在”
namespace CodeExcercise
{
[TestClass]
public class TestClass
{
[TestMethod]
public void Test()
{
var cars = new List<Car>()
{
new Car() { owner.Firstname = "Brian", Lastname = "Badonde", Cost = 5, Registered = DateTime.Now},
};
new PrintMethod().PrintReport(cars, "CR.csv");
var outPut = File.ReadAllLines("CR.csv");
Assert.AreEqual(1, outPut.Count());
}
}
public class Owner
{
public string Firstname;
public string Lastname;
}
public class Car
{
public Owner owner;
public double Cost;
public DateTime Registered;
}
答案 0 :(得分:5)
您用来在此处设置owner
属性的语法不正确:
new Car() { owner.Firstname = "Brian", Lastname = "Badonde", Cost = 5, Registered = DateTime.Now}
您将使用与创建Owner
对象相同的语法来创建Car
对象。例如:
new Car()
{
owner = new Owner()
{
Firstname = "Brian",
Lastname = "Badonde"
},
Cost = 5,
Registered = DateTime.Now
}
您可以随意嵌套它,每个对象创建都是自己的操作。
答案 1 :(得分:3)
您必须创建新的Owner
对象:
new Car
{
owner = new Owner { Firstname = "Brian", Lastname = "Badonde" },
Cost = 5,
Registered = DateTime.Now
};
答案 2 :(得分:3)
我有一个Car类,它具有Owner属性。所有者具有两个属性:名字和姓氏
我想你的意思是
我有一个汽车课,我想将所有者指定为嵌入式初始化器。
在这种情况下,您必须创建属性的类型并使用相同的内联初始化程序来设置其属性:
new Car
{
Cost = 5,
Registered = DateTime.Now,
Owner = new Owner
{
Firstname = "Brian",
Lastname = "Badonde"
},
}
我使用了大写的属性名称,因为Microsoft指南建议所有属性都以大写字符开头。