C#:如何为部分类中的属性设置默认值? [英] C#: How to set default value for a property in a partial class?

查看:854
本文介绍了C#:如何为部分类中的属性设置默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C#还是很陌生,所以请多包涵...

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 ...
}

我想初始化两个数据成员: IsSomething True SomeList new List< string>()。通常,我会在构造函数中执行此操作,但是因为它是局部类,所以我不想触及构造函数(是吗?)。

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?).

什么是最好的方法

谢谢

PS我在ASP.NET MVC中工作,为某些功能添加了功能模型,因此是局部类。

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

推荐答案

已针对C#6更新

C#6添加了为自动属性分配默认值的功能。该值可以是任何表达式(不必为常数)。下面是一些示例:

C# 6 has added the ability to assign a default value to auto-properties. The value can be any expression (it doesn't have to be a constant). Here's a few examples:

// Initialize to a string literal
public string SomeProperty {get;set;} = "This is the default value";

// Initialize with a simple expression
public DateTime ConstructedAt {get;} = DateTime.Now;

// Initialize with a conditional expression
public bool IsFoo { get; } = SomeClass.SomeProperty ? true : false;






原始答案

可以在类构造函数中初始化自动实现的属性,但不能在属性本身上初始化。

Automatically implemented properties can be initialized in the class constructor, but not on the propery itself.

public SomeModel
{
    IsSomething = false;
    SomeList = new List<string>();
}

...或您可以使用字段支持的属性(工作量稍多)并初始化字段本身...

...or you can use a field-backed property (slightly more work) and initialize the field itself...

private bool _IsSomething = false;
public bool IsSomething
{
    get { return _IsSomething; }
    set { _IsSomething = value; }
}

更新:我上面的答案没有阐明在局部类中存在的问题。 Mehrdad的答案提供了使用部分方法的解决方案,这与我的第一个建议是一致的。我的第二个建议是使用非自动实现的属性(手动实现的属性?)来解决这种情况。

Update: My above answer doesn't clarify the issue of this being in a partial class. Mehrdad's answer offers the solution of using a partial method, which is in line with my first suggestion. My second suggestion of using non-automatically implemented properties (manually implemented properties?) will work for this situation.

这篇关于C#:如何为部分类中的属性设置默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆