2017-10-18 44 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; 
} 
相關問題