【问题标题】:Setting a default value for property that is mutable in C# [duplicate]为 C# 中可变的属性设置默认值 [重复]
【发布时间】:2016-02-17 16:32:44
【问题描述】:

我有财产

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 来说非常非常新)

【问题讨论】:

  • 但我没有使用 c# 吗?你的意思是说:但我没有使用 c# 6.0?
  • 无论如何,如果您是6.0之前的版本,请使用构造函数进行初始化。
  • 所以添加一个default constructor 并在那里初始化它。顺便说一句,你真的想使用partial 类吗?如果你需要一个分部类,那是因为一些类定义是自动生成的。是这样吗?如果不是,使用partial 是一种滥用,可能表明一个类承担了太多责任(并且已经变得太大)。对于手写代码,部分定义类只会掩盖代码的意图。
  • 已编辑,未使用 c# 6,抱歉

标签: c#


【解决方案1】:

只需在构造函数中设置即可:

public partial class Test
{
    public int Id { get; set; }
    public string Test1 { get; set; }
    public int Active { get; set; }

    public Test()
    {
        Active = 1;
    }
}

我认为这比仅仅为了默认而避免自动实现的属性更简单......

【讨论】:

    【解决方案2】:

    在构造函数中初始化它:

    public partial class Test
    {
        public int Active { get; set; }
    
        public Test()
        {
            Active = 1;
        }
    }
    

    【讨论】:

      【解决方案3】:
      // 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; }
          }
      

      【讨论】:

      • 太棒了,现在我看到了get set的实用程序,几天前就开始使用c#了
      • 它变得更好了。属性非常强大。你可以做的不仅仅是一个简单的get; set;,甚至不仅仅是一个简单的作业,
      【解决方案4】:

      在 C#6 之前的版本中执行此操作的默认方法要冗长得多,但它只是语法 - 这是等效的:

      public class Foo
      {
          private int _bar = 1;
          public int Bar
          {
              get { return _bar; }
              set { _bar = value; }
          }
      }
      

      【讨论】:

      • 非常感谢,不胜感激
      猜你喜欢
      • 2012-10-14
      • 1970-01-01
      • 2012-04-07
      • 1970-01-01
      • 2010-10-16
      • 1970-01-01
      • 2011-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多