[英]How do I set a property to a default value in C#?
so for a user control, I have所以对于用户控件,我有
public int Count { get; set; }
so that I can use this.Count
in another method.这样我就可以在另一种方法中使用this.Count
。 The trouble is, I want to set a default for Count to something like 15
.问题是,我想将 Count 的默认值设置为15
。 How do I set defaults?如何设置默认值?
In the constructor of the userControl在 userControl 的构造函数中
public YourUserControl(){
Count = 15;
}
You will need to set it in the constructor of your class.您需要在 class 的构造函数中设置它。
For example:例如:
public partial class YourControl : UserControl
{
public int Count { get; set; }
public YourControl()
{
InitializeComponent();
// Set your default
this.Count = 15;
}
}
Alternatively, if you use a backing field, you can set it inline on the field :或者,如果您使用支持字段,则可以将其设置为内联字段:
public partial class YourControl : UserControl
{
private int count = 15;
public int Count
{
get { return this.count; }
set { this.count = value; }
}
If you want the object that creates your control to set the default, then they can use a property initializer when they new the control.如果您希望创建控件的 object 设置默认值,那么他们可以在新建控件时使用属性初始化程序。 If you want to set a default for the control, then you would set those defaults in the constructor.如果要为控件设置默认值,则可以在构造函数中设置这些默认值。
You set the default values for automatic properties in the constructor of the class.在 class 的构造函数中设置自动属性的默认值。
public MyClass()
{
Count = 15;
}
Or alternatively to setting the value in the constructor, which will likely work just fine here, use the long approach.或者,在构造函数中设置值,这可能在这里工作得很好,使用长方法。
int _count = 15;
public int Count {
get { return _count; }
set { _count = value; }
}
Sometimes this way is useful if the appropriate constructor is not called for some reason (such as some Serialization/Activation techniques).有时,如果由于某种原因(例如某些序列化/激活技术)未调用适当的构造函数,则这种方法很有用。
Happy coding.快乐编码。
Instead of using an auto implemented property you can write your own property based on an underlying field containing your default value:您可以基于包含默认值的基础字段编写自己的属性,而不是使用自动实现的属性:
private int _count = 15;
public int Count
{
get { return _count; }
set { _count = value; }
}
You can use the DefaultValueAttribute.您可以使用 DefaultValueAttribute。 More info here: http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx更多信息: http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx
This question is a possible duplicate: How do you give a C# Auto-Property a default value?这个问题可能重复: How do you give a C# Auto-Property a default value?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.