2017-10-18 28 views
-2

如何在正确的方式使用属性里面的方法。我在互联网上搜索,但我找不到属性是使用里面的方法,将返回值。如何在C#中使用属性里面的方法

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”方法获取价值,它是代码右上方?

+0

[:资源下载](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-properties)。 – Sinatr

+0

只需使用“return this.ShiftTime - this.BreakTime;”不需要您的参数(班次,休息时间)。 – Flocke

+0

没有使用“筛选”和“breaktime”局部变量的功能。 –

回答

1

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

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

注意,这是的方法,而不是 - 属性将有一个像访问的方法的语法方式属性:

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

0

没有使用“筛选”和“breaktime”局部变量进入函数。只需使用返回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; 


    } 
0

您可以通过它定义get方法定义属性作为一个计算的,。

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

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

private\public int _calculatePlannedProductionTime (int shift, int break) 
{ 
return shift - break; 
} 
相关问题