有没有一种方法可以设置类中字段的默认值,从而不必在创建时指定值?

时间:2018-08-23 08:45:44

标签: c#

我上了这个课:

public class ParamViewModel: BaseViewModel
{
    int _id;
    public int Id
    {
        get => _id;
        set => SetProperty(ref _id, value);
    }

    string _name;
    public string Name
    {
        get => _name;
        set => SetProperty(ref _name, value);
    }

    bool _isSelected;
    public bool IsSelected
    {
        get => _isSelected;
        set => SetProperty(ref _isSelected, value);
    }

}

public ParamViewModel[] STIVM { get; set; } = new[] {
        new ParamViewModel{  Id = 0, Name = STI.Zero.Text(), IsSelected = false} ,
        new ParamViewModel{  Id = 1, Name = STI.ZeroFive.Text(), IsSelected = false} ,
        new ParamViewModel{  Id = 2, Name = STI.One.Text(), IsSelected = false} ,
        new ParamViewModel{  Id = 3, Name = STI.OneFive.Text(), IsSelected = false} ,
        new ParamViewModel{  Id = 4, Name = STI.Two.Text(), IsSelected = false} ,
        new ParamViewModel{  Id = 5, Name = STI.Three.Text(), IsSelected = false} ,
        new ParamViewModel{  Id = 6, Name = STI.Four.Text(), IsSelected = false} ,
    };

是否有一种方法可以使IsSelected默认情况下为假?

4 个答案:

答案 0 :(得分:3)

当然可以,在声明时将_isSelected设置为false:

bool _isSelected = false;

实际上,如vc 74所指出的,在类的构造函数中设置该值时,您可以实现完全相同的操作。

但这毫无意义,因为false已经 bool的默认值。

因此,让我们看一下它对int属性的工作方式,该属性应默认为-1而不是“正常”默认值零:

int _id = -1;
public int Id
{
    get => _id;
    set => SetProperty(ref _id, value);
}

答案 1 :(得分:1)

我认为您实际上是指在建筑上打电话给财产设定者:

gender: <randomElement(['Homme', 'Femme'])>
if $gender == 'Homme'
    title: 'Monsieur'
else if $gender == 'Femme'
    title: 'Madame'

答案 2 :(得分:0)

将isSelected更改为

bool _isSelected = false;

答案 3 :(得分:0)

_isSelected声明false变量。

bool _isSelected = false;