如何在ASP.NET中为自动实现的属性设置默认值 [英] How to set default value for Auto-Implemented Properties in ASP.NET

查看:357
本文介绍了如何在ASP.NET中为自动实现的属性设置默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道C#3.0带有自动实现属性的新功能,我喜欢它,因为我们不必在此声明额外的私有变量(与之前的属性相比),而我早先使用的是Property即

I came to know that C# 3.0 comes with a new feature of Auto-Implemented Properties,I liked it as we don't have to declare extra private varible in this (compare to earlier property), earlier I was using a Property i.e.

private bool isPopup = true;
public bool IsPopup
{
    get
    {
      return isPopup;
    }
    set
    {
      isPopup = value;
    }
}

现在我已将其转换为自动实施的属性,即

Now I've converted it into Auto-Implemented property i.e.

public bool IsPopup
{
    get; set;
}

我想将此属性的默认值设置为true,甚至在page_init方法中也不要使用它,我尝试了但没有成功,有人可以解释如何做吗?

I want to set the default value of this property to true without using it not even in page_init method, I tried but not succeeded, Can anyone explain how to do this?

推荐答案

您可以在默认构造函数中初始化属性:

You can initialize the property in the default constructor:

public MyClass()
{
   IsPopup = true;
}

使用C#6.0,可以像普通成员字段一样在声明处初始化属性

With C# 6.0 it is possible to initialize the property at the declaration like normal member fields:

public bool IsPopup { get; set; } = true;  // property initializer

现在甚至可以创建一个真正的只读自动属性,您可以直接对其进行初始化,也可以在构造函数中对其进行初始化,而无需在该类的其他方法中进行设置.

It is now even possible to create a real read-only automatic property which you can either initialize directly or in the constructor, but not set in other methods of the class.

public bool IsPopup { get; } = true;  // read-only property with initializer

这篇关于如何在ASP.NET中为自动实现的属性设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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