C# DefaultValue 属性不起作用
C# DefaultValue attribute not working
我正在使用C#windows窗体控件库程序创建自己的控件,代码如下:
public partial class MyControl : UserControl
{
public MyControl()
{
InitializeComponent();
}
private float mMinValue;
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
[Category("Design") , DefaultValue(0.0)]
public float MinValue
{
get { return mMinValue; }
set { mMinValue = value; }
}
private float mMaxValue;
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
[Category("Design") , DefaultValue(1.0)]
public float MaxValue
{
get { return mMaxValue; }
set { mMaxValue = value; }
}
}
程序运行时,MinValue和MaxValue的默认值都是0,那么如何正确设置默认值呢?
public partial class MyControl : UserControl
{
//Declare your variables here
private float mMinValue = 0.0;
private float mMaxValue = 1.0;
//Leave it
public MyControl()
{
InitializeComponent();
}
}
Default value 属性仅指示设计者属性 的默认值是什么。它不会将其设置为 属性 后面的成员的实际值。 MSDN page for the default value attribute:
上也提到了这一点
(在备注部分)
Note
A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code.
因此,正如其他人已经提到的,您需要自己在代码中设置这些值(我喜欢在构造函数中而不是在私有成员的声明中进行设置,但我认为这只是一个问题个人喜好)。
如果我理解正确,你可以尝试使用 DefaultValueAttribute,引用:
A DefaultValueAttribute will not cause a member to be automatically
initialized with the attribute's value.You must set the initial value
in your code.
要设置默认值,您应该使用构造函数。
public MyControl()
{
MinValue = 0;
MaxValue = 100;
InitializeComponent();
}
我正在使用C#windows窗体控件库程序创建自己的控件,代码如下:
public partial class MyControl : UserControl
{
public MyControl()
{
InitializeComponent();
}
private float mMinValue;
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
[Category("Design") , DefaultValue(0.0)]
public float MinValue
{
get { return mMinValue; }
set { mMinValue = value; }
}
private float mMaxValue;
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
[Category("Design") , DefaultValue(1.0)]
public float MaxValue
{
get { return mMaxValue; }
set { mMaxValue = value; }
}
}
程序运行时,MinValue和MaxValue的默认值都是0,那么如何正确设置默认值呢?
public partial class MyControl : UserControl
{
//Declare your variables here
private float mMinValue = 0.0;
private float mMaxValue = 1.0;
//Leave it
public MyControl()
{
InitializeComponent();
}
}
Default value 属性仅指示设计者属性 的默认值是什么。它不会将其设置为 属性 后面的成员的实际值。 MSDN page for the default value attribute:
上也提到了这一点
(在备注部分)
Note
A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value. You must set the initial value in your code.
因此,正如其他人已经提到的,您需要自己在代码中设置这些值(我喜欢在构造函数中而不是在私有成员的声明中进行设置,但我认为这只是一个问题个人喜好)。
如果我理解正确,你可以尝试使用 DefaultValueAttribute,引用:
A DefaultValueAttribute will not cause a member to be automatically initialized with the attribute's value.You must set the initial value in your code.
要设置默认值,您应该使用构造函数。
public MyControl()
{
MinValue = 0;
MaxValue = 100;
InitializeComponent();
}