How to set a constant decimal value

こ雲淡風輕ζ 提交于 2019-12-30 05:38:17

问题


I'm using C# to set a default value for a decimal value in my config class

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

but it won't be compiled and throws an error

An attribute argument must be a constant expression, typeof expression

I found a post says: "It's not a bug. "1000M" is merely shorthand for "new Decimal(1000)", which involves a method call, which means it's not considered a constant. Just because the compile lets you pretend it's a constant most of the time, doesn't mean you can all of the time."

Now, how do I workaround it?


回答1:


I finally found out it I enter "440" instead of 440m or 440. It got compiled and runs well




回答2:


I found that if you set a default value for a decimal property and specified that value in quotes, it did not work for me with a WinForms control and .NET 3.5.

When ever I right clicked on the property in the designer "Properties" window and selected the "Reset" option I got the message "Object of type 'System.String' cannot be converted to type 'System.Decimal'.

To get it to work I had to use the same code as tphaneuf suggested i.e.

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



回答3:


You should place 440 inside quotation marks, like this:

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



回答4:


Just use 440 and leave out the 'M'. I get no compilation errors, and this program works as expected:

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


来源:https://stackoverflow.com/questions/1236402/how-to-set-a-constant-decimal-value

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