簡體   English   中英

如何在C#中的方法內部使用屬性

[英]How to use Property inside Method in C#

如何以正確的方式使用 Property inside 方法。 我在互聯網上搜索,但我找不到在將返回值的方法中使用的屬性。

 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”方法中獲取值,是上面的代碼嗎?

您的示例不是很清楚,因為您傳入了兩個參數,但隨后在計算中忽略了它們。 但是,如果您的意圖是讓屬性返回計算出的 PlannedProductionTime,它可以是這樣的:

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

請注意,這不是方法 - 屬性是一種語法方式,可以像訪問屬性一樣訪問方法:

OET myOet = new OET(); intplannedProductionTime = myOet.PlannedProductionTime;

沒有使用“sift”和“breaktime”局部變量進入is函數。 只需使用返回 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;


    }
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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM