如何在C#中使用Method里面的属性

时间:2017-10-18 06:45:03

标签: c# oop

如何正确使用方法内部的属性。我在互联网上搜索,但我发现在方法中使用的属性将被返回值。

 public class OET
{


    public int ShiftTime { get; set; }
    public int BreakTime { get; set; }
    public int DownTime { get; set; }
    public int ProductionTarget { get; set; }

    public int IdealRunRate { get; set; }
    public int PrductionOneShift { get; set; }
    public int RejectedProduct { get; set; }

    public int planedProductionTime(int shift, int breaktime) {

        shift = ShiftTime;
        breaktime = BreakTime;

        return shift - breaktime;

    }

我想使用属性从" PlanedProductionTIme"中获取价值。方法,它是上面的代码吗?

3 个答案:

答案 0 :(得分:1)

您的示例不是很清楚,因为您传递了两个参数,但在计算中忽略它们。但是如果你的意图是让一个属性返回计算出的PlannedProductionTime,它可以是这样的:

public int PlannedProductionTime
{
    get { return ShiftTime - BreakTime; }
}

请注意,这是方法的而不是 - 属性是一种语法方式,可以像访问属性一样访问方法:

OET myOet = new OET();    int plannedProductionTime = myOet.PlannedProductionTime;

答案 1 :(得分:0)

没有使用“sift”和“breaktime”局部变量为函数。只需使用return ShiftTime-BreakTime。

public int method2() {
///here you are getting the peroperties value and doing calculations returns result.
    return ShiftTime -BreakTime;

}

如果您的要求是设置属性值。

 public void method1(int shift, int breaktime) {

      ShiftTime=  shift ;
     BreakTime  = breaktime;


    }

答案 2 :(得分:0)

public int PlanedProductionTime { get { return ShiftTime - BreakTime; } }

您可以通过在其中定义get方法将属性定义为计算属性。

更多解决方案 - 您可以定义一个单独的函数并在get中调用它。如果你想做一些更复杂的计算需要在类中的其他地方使用它会有所帮助 - 私有或外部类 - 公共。

public int PlanedProductionTime { get { return _calculatePlannedProductionTime( ShiftTime, BreakTime); } }

private\public int _calculatePlannedProductionTime (int shift, int break)
{
 return shift - break;
}