如何在我的类中启用算术运算符 [英] How Do I Enable Arithmetic Operators In My Classes

查看:61
本文介绍了如何在我的类中启用算术运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它一直告诉我,我不能在double,decimal,int数据类型上使用这些运算符。我知道我可以,但如何?





It keeps telling me that i cant use these operators on the double,decimal,int data types. i know i can but how?


public decimal Total { get; set; }
        public decimal Discount { get
            {
            double dis=0;
            dis=Total-(Total*0.05);
             }
            set; }
        public decimal Deposit { get; set; }









我被告知有'使用'参考我需要使用。



我是MVC5的新手





ive been told that there is a 'using'reference i need to use.

I am new to MVC5

推荐答案

你正在混合 double dis )和 decimal 总计)在你的计算中你得到一个错误
You are mixing double (dis) and decimal (Total) in your calculation so you are getting an error
Quote:

运算符'*'不能应用于类型的操作数'decimal'和'double'

Operator '*' cannot be applied to operands of type 'decimal' and 'double'



这是因为 0.05 类型为 double 。要将其转换为十进制,请将M添加到其末尾,如此


This is because 0.05 is of type double. To convert it to decimal add an 'M' to the end of it like this

dis = Total - (Total * 0.05M);



但是你还在混合 double 十进制值,然后会得到一个不同的错误


However you are still mixing double and decimal values and will then get a different error

Quote:

无法将类型'decimal'隐式转换为'double'。存在显式转换(你是否错过了演员?)

Cannot implicitly convert type 'decimal' to 'double'. An explicit conversion exists (are you missing a cast?)

为了解决这个问题,将计算结果转换为双

To get around that cast the result of the calculation to a double

dis = (double)(Total - (Total * 0.05M));

或更好,与您的变量类型一致

or better yet, be consistent with your variable types


这篇关于如何在我的类中启用算术运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆