一个关于 DTO 的简单问题,我有一个 DTO 类汽车,里面还有一些汽车模型的子类。
public class Cars
{
public Ferrari FerrariModel { get; set; }
public Porshe PorsheModel {get; set; }
public Mustang MustangModel { get; set; }
}
public class Ferrari
{
public string collor{ get; set; }
public int year{ get; set; }
public double price{ get; set; }
}
而Porshe和Mustang就是一模一样的法拉利。问题是我现在不知道如何进行。我尝试类似的东西
Cars cars = new Cars();
FerrariModel fm = new FerrariModel();
cars.FerrariModel.collor = txtCollor.Text;
而且它不起作用,因为我在 cars.FerrariModel.collor 中收到以下错误 ->“对象引用未设置段落嗡嗡声对象的实例。嗡嗡声对象声明”。 我必须承认,我什至不知道它“是可能的”,或者我是否在“发明编程”,所以任何帮助都会很棒。
- 为什么只使用一个类?因为需要在参数中传递单个 DTO:save(Cars car);更新(汽车汽车)
- 使用第二个分离类会迫使我“重载”方法:save(Cars car);保存(法拉利法拉利);
- 如果我使用单个类(没有 Ferrari、Porshe 和 Mustang),程序可以工作,但我的 InteliSense 中有很多变量,超过 50 个。
谢谢。
最佳答案
您需要将您的 fm
实例分配给您的 Cars.FerarriModel
属性。
Cars cars = new Cars();
FerrariModel fm = new FerrariModel();
cars.FerrariModel = fm;
cars.FerrariModel.collor = txtCollor.Text;
甚至只是:
Cars cars = new Cars();
cars.FerrariModel = new FerrariModel() { collor = txtCollor.Text };
关于c# - 一个内部有多个类的 DTO 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35736204/