如何设置常量小数值

我正在使用C#为我的配置类中的十进制值设置默认值

public class ConfigSection : ConfigurationSection { [ConfigurationProperty("paymentInAdvanceAmount", **DefaultValue = 440m**)] public decimal PaymentInAdvanceAmount { get { return (decimal)base["paymentInAdvanceAmount"]; } set { base["paymentInAdvanceAmount"] = value; } } } 

但它不会被编译并抛出错误

属性参数必须是常量表达式,typeof表达式

我找到一个post说: “这不是一个错误。”1000M“只是”新十进制(1000)“的简写,它涉及一个方法调用,这意味着它不被认为是一个常量。只是因为编译让你假装它是一个大部分时间不变,并不意味着你可以一直这样。“

现在,我该如何解决它?

我终于发现它输入“440”而不是440m或440.它编译并运行良好

我发现如果你设置一个十进制属性的默认值并用引号指定该值,它对我使用WinForms控件和.NET 3.5不起作用。

当我在设计器“属性”窗口中右键单击属性并选择“重置”选项时,我收到消息“类型为’System.String’的对象’无法转换为’System.Decimal’类型。

为了使它工作,我不得不使用与tphaneuf建议相同的代码,即

 [DefaultValue(typeof(Decimal), "440")] public decimal TestValue { get; set; } 

只需使用440并省略’M’。 我没有编译错误,这个程序按预期工作:

 namespace WindowsApplication5 { public partial class Form1 : Form { public Form1( ) { InitializeComponent( ); AttributeCollection attributes = TypeDescriptor.GetProperties( mTextBox1 )[ "Foo" ].Attributes; DefaultValueAttribute myAttribute = ( DefaultValueAttribute ) attributes[ typeof( DefaultValueAttribute ) ]; // prints "440.1" MessageBox.Show( "The default value is: " + myAttribute.Value.ToString( ) ); } } class mTextBox : TextBox { private decimal foo; [System.ComponentModel.DefaultValue( 440.1 )] public decimal Foo { get { return foo; } set { foo = value; } } } } 

你应该把440放在引号内,如下所示:

 [ConfigurationProperty("paymentInAdvanceAmount", DefaultValue = "440")]