为在 C# 中可变的属性设置默认值
本文关键字:属性 设置 默认值 为在 | 更新日期: 2023-09-27 18:34:57
我有一个属性
public int active { get; set; }
在我的数据库中,默认值为 1。如果没有另行指定,我希望此属性默认为 1
public partial class test
{
public int Id { get; set; }
public string test1 { get; set; }
public int active { get; set; }
}
我看到在 c# 6 中你可以做
public int active { get; set; } = 1
但我没有使用 c# 6 :(。谢谢你的建议。(对 c#/OOP 非常非常陌生(
只需在构造函数中设置它:
public partial class Test
{
public int Id { get; set; }
public string Test1 { get; set; }
public int Active { get; set; }
public Test()
{
Active = 1;
}
}
我认为这比仅仅为了默认值而避免自动实现的属性更简单......
在构造函数中初始化它:
public partial class Test
{
public int Active { get; set; }
public Test()
{
Active = 1;
}
}
// option 1: private member
public partial class test
{
private int _active = 1;
public int Id { get; set; }
public string test1 { get; set; }
public int active
{
get {return _active; }
set {_active = value; }
}
}
// option 2: initialize in constructor
public partial class test
{
public test()
{
active = 1;
}
public int Id { get; set; }
public string test1 { get; set; }
public int active { get; set; }
}
在 C#6 之前执行此操作的默认方法要详细得多,但它只是语法 - 这是等效的:
public class Foo
{
private int _bar = 1;
public int Bar
{
get { return _bar; }
set { _bar = value; }
}
}