C# read-only calculated properties, should they be methods?

前端 未结 11 1213
刺人心
刺人心 2021-01-31 13:55

I have several entities that have calculated fields on them such as TotalCost. Right now I have them all as properties but I\'m wondering if they should actually be methods. Is

11条回答
  •  一个人的身影
    2021-01-31 14:39

    MSDN gives information about this here

    Class library designers often must decide between implementing a class member as a property or a method. In general, methods represent actions and properties represent data.

    Which one do you think it is? An action calculate/getLaborCost or data?

    WorkOrder workOrder = new WorkOrder();
    workOrder.LaborHours = 8;
    workOrder.LaborRate = 20;
    
    decimal cost = workOrder.LaborCost; // This is OK here
    

    but if you are going to do this for the same object also:

    worOrder.LaborHours = 18;
    decimal newCost = workOrder.LaborCost 
    

    Now this cannot be a property. It would be a lot better to be a method.

提交回复
热议问题