How to set default value for Auto-Implemented Properties in ASP.NET [duplicate]

十年热恋 提交于 2019-12-09 07:41:15

问题


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

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?


回答1:


You can initialize the property in the default constructor:

public MyClass()
{
   IsPopup = true;
}

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



回答2:


Attributes specified for an auto property do not apply to the backing field, so an attribute for a default value won't work for this type of property.

You can, however, initialize an auto property:

VB.NET

Property FirstName As String = "James"
Property PartNo As Integer = 44302
Property Orders As New List(Of Order)(500)

C# 6.0 and above

public string FirstName { get; set; } = "James";
public int PartNo { get; set; } = 44302;
public List<Order> Orders { get; set; } = new List<Order>(500);

C# 5.0 and below

Unfortunately, C# versions below 6.0 do not support this, so you have to initialize the default values for auto properties in the constructor.




回答3:


Have you tried DefaultValueAttribute




回答4:


using System.ComponentModel;

[DefaultValue(true)]
public bool IsPopup
{
    get
    {
      return isPopup;
    }
    set
    {
      isPopup = value;
    }
}



回答5:


You can use default property value like below

One advantage of this method is you don't need to check null values for Boolean types

using System.ComponentModel; 

public class ClassName
 {
   [DefaultValue(true)]
   public bool IsPopup{ get; set; }
 }


来源:https://stackoverflow.com/questions/8293918/how-to-set-default-value-for-auto-implemented-properties-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!