C#: How to set default value for a property in a p

2019-06-14 22:16发布

I'm very new to C# so please bear with me...

I'm implementing a partial class, and would like to add two properties like so:

public partial class SomeModel
{
    public bool IsSomething { get; set; }
    public List<string> SomeList { get; set; }

    ... Additional methods using the above data members ...
}

I would like to initialize both data members: IsSomething to True and SomeList to new List<string>(). Normally I would do it in a constructor, however because it's a partial class I don't want to touch the constructor (should I?).

What's the best way to achieve this?

Thanks

PS I'm working in ASP.NET MVC, adding functionality to a a certain model, hence the partial class.

8条回答
迷人小祖宗
2楼-- · 2019-06-14 22:43

You can't have two constructors in two parts of a partial class. However, you can use partial methods to accomplish something like it:

// file1:
partial void Initialize();
public Constructor() {
    // ... stuff ... initialize part 1
    Initialize();
}

// file2:
void Initalize() {
    // ... further initializations part 2 might want to do
}

If no parts of a partial class defines the partial method, all calls to it would be omitted.

查看更多
乱世女痞
3楼-- · 2019-06-14 22:50

For user of version 6.0 of C#, it's possible to initialize the properties like this :

public bool IsSomething { get; set; } = true;
public List<string> SomeList { get; set; } = new List<string>();
查看更多
登录 后发表回答