简体   繁体   中英

Can you do calculations in the get/set ? c#

Can you do a calculation in the set clause? and it then returns the total when implemented?`

    public decimal TotalCost
     { 
      set
      { this.costTotal = (decimal)prodCost + (decimal)shipping + (decimal)insurance)}
       get
      { return this.costTotal}
     }

Can you do a calculation in the set clause?

Absolutely. However, in your specific case, it is not clear why would you do that. The point of a setter is to allow users of a class to safely manipulate fields of its objects. This is done using the value keyword. Since you are only interested in calculating a value using existing data, there is no reason to even use a setter. it seems more suitable to do the calculation in a getter only property:

public decimal TotalCost
{ 
    get
    {
        return (decimal)prodCost + (decimal)shipping + (decimal)insurance);
    }
}

A shorter version of the above code:

public decimal TotalCost => (decimal)prodCost + (decimal)shipping + (decimal)insurance;

What others said, but maybe you're looking for a method:

public decimal CostTotal { get; private set; }

(...)

public void SetTotalCost(decimal prodCost, decimal shipping, decimal insurance)
{
   this.CostTotal = prodCost + shipping + insurance);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM