简体   繁体   English

如何在C#中的方法内部使用属性

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

How to use Property inside method in right way.如何以正确的方式使用 Property inside 方法。 I was searching on the internet but I can't found property is used inside method that will be returned value.我在互联网上搜索,但我找不到在将返回值的方法中使用的属性。

 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;

    }

I would like to use property to get value from "PlanedProductionTIme" method, is it code above right?我想使用属性从“PlanedProductionTIme”方法中获取值,是上面的代码吗?

Your example isn't very clear, because you're passing in two parameters, but then ignoring them in your calculation.您的示例不是很清楚,因为您传入了两个参数,但随后在计算中忽略了它们。 But if your intention was to have a property returning the calculated PlannedProductionTime, it can go like this:但是,如果您的意图是让属性返回计算出的 PlannedProductionTime,它可以是这样的:

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

Note that this is instead of the method - a property is a syntactic way to have a method accessed like a property:请注意,这不是方法 - 属性是一种语法方式,可以像访问属性一样访问方法:

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

there is no use of "sift" and "breaktime" local variable into is function.没有使用“sift”和“breaktime”局部变量进入is函数。 just use return ShiftTime-BreakTime.只需使用返回 ShiftTime-BreakTime。

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

}

if your requirement is to set the properties value.如果您的要求是设置属性值。

 public void method1(int shift, int breaktime) {

      ShiftTime=  shift ;
     BreakTime  = breaktime;


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

You can define the property as a calculated ones, by defining the get method in it.您可以通过在其中定义 get 方法将属性定义为计算属性。

More solutions - you can define a separate function and call it inside get.更多解决方案 - 您可以定义一个单独的函数并在 get 中调用它。 It will help if you want to do some more complex calculations which needs to be used somewhere else in the class - private or outside class - public.如果您想做一些需要在类中的其他地方使用的更复杂的计算 - 私有或外部类 - 公共,它将有所帮助。

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