gpt4 book ai didi

c# - 在模型中实现默认值

转载 作者:太空狗 更新时间:2023-10-29 17:29:00 24 4
gpt4 key购买 nike

在 C# MVC 应用程序中,我有一个模型 Customer,它可以从数据库中检索,也可以作为新模型创建。

如果我要创建一个新客户,设置默认值(例如 CusotmerLevel 默认为 1)的正确方法是什么?

我应该为新雇员和从数据库中检索的雇员使用不同的构造函数,还是采用其他方式?

最佳答案

假设它是一个 POCO,我总是发现构造函数可以很好地建立默认值。我通常会借此机会声明诸如 CreatedDate 之类的内容。当它从数据库中检索时,公共(public)属性无论如何都会被数据库值覆盖。

public class Customer
{
public Int32 Id { get; set; }
public Int32 CustomerLevel { get; set; }
/* other properties */

public Customer()
{
this.CustomerLevel = 1;
}
}

更新

而且,如果您使用的是 C# 6.0,请查看 auto-property initializers :

public class Customer
{
public Int32 Id { get; set; } = 1;
public Int32 CustomerLevel { get; set; }
/* other properties */
}

关于c# - 在模型中实现默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15901892/

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