相关疑难解决方法(0)

如何为C#Auto-Property提供默认值?

如何为C#Auto-Property提供默认值?我要么使用构造函数,要么还原为旧语法.

使用构造函数:

class Person 
{
    public Person()
    {
        Name = "Initial Name";
    }
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

使用普通属性语法 (使用默认值)

private string name = "Initial Name";
public string Name 
{
    get 
    {
        return name;
    }
    set
    {
        name = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?

c# automatic-properties

1773
推荐指数
16
解决办法
78万
查看次数

初始化C#自动属性

我习惯写这样的课程:

public class foo {
  private string mBar = "bar";
  public string Bar {
    get { return mBar; }
    set { mBar = value; }
  }
  //... other methods, no constructor ...
}
Run Code Online (Sandbox Code Playgroud)

将Bar转换为自动属性看起来既方便又简洁,但是如何在不添加构造函数并将初始化放在那里的情况下保留初始化?

public class foo2theRevengeOfFoo {
  //private string mBar = "bar";
  public string Bar { get; set; }
  //... other methods, no constructor ...
  //behavior has changed.
}
Run Code Online (Sandbox Code Playgroud)

您可以看到添加构造函数并不符合我应该从自动属性中获得的省力.

这样的事情对我来说更有意义:

public string Bar { get; set; } = "bar";
Run Code Online (Sandbox Code Playgroud)

c# initialization automatic-properties

180
推荐指数
3
解决办法
15万
查看次数

标签 统计

automatic-properties ×2

c# ×2

initialization ×1