如何在方法参数中引用变量?

时间:2019-11-17 14:06:41

标签: c# unity3d methods parameters

抱歉,如果标题不正确,我真的不知道我要查找的名称

假设我有这个课程:

public class Potion(){

public int WaterAmount;
public int ReagentAmount;

}

现在,如果我想使用一种方法来检查药水或试剂中的试剂量,


    public int GetWaterAmount ( Potion pot ){

    return pot.WaterAmount;

    }
    public int GetReagentAmount ( Potion pot ){

    return pot.ReagentAmount;

    }


现在我的问题是如何将这两种方法合而为一,这样我就可以输入要检查的液体的参数了?这是我要找的一些无效语法:

    public int GetAmount ( Potion pot, int SelectedLiquid){

    return pot.SelectedLiquid;

    }

    void main(){

    GetAmount(pot, WaterAmount);
    GetAmount(pot, ReagentAmount);
    }

从本质上讲,如何使一个参数(选定的液体)引用类中的不同变量(水量或试剂量)?

或者这是不可能的,对于每个要检查的变量,我确实需要一种方法吗?

3 个答案:

答案 0 :(得分:1)

您正在寻找一个枚举。

enum LiquidType
{
    Water,
    Reagent
}

public int GetAmount ( Potion pot, LiquidType type)
{
    switch (type)
    {
       case LiquidType.Water:
           return pot.WaterAmount;
       case LiquidType.Reagent:
           return pot.ReagentAmount;
       default:
           return 0;
    }

void main(){

GetAmount(pot, LiquidType.Water);
GetAmount(pot, LiquidType.Reagent);
}

答案 1 :(得分:0)

只需一点点逻辑就可以做到。在这种情况下,参数“ SelectedLiquid”可以为布尔值,也可以为int,并且您可以检查该值是否具有引用所需类变量的适当值。通常,这不是一个好主意,您不想有多个if-else问卷或类似的switch语句。更好的方法是定义一个枚举,该枚举将引用特定的类变量,但是即使这样,也必须具有基于switch或if-else的逻辑才能在GetAmount方法中检索适当的值。

更好的方法是真正有两种方法来获取所需的变量。但是,如果您需要那些吸气剂,或者您希望班级为您做其他事情,则需要重新考虑。查看这是否是一个选项:What is the { get; set; } syntax in C#?

要重复:

  1. 您可以基于其他信息来执行此操作,可以使用枚举和if-else / switch来检索适当的属性

  2. 最好是使用那些特定的方法,但也许可以使用公共访问器,请参见提供的链接:What is the { get; set; } syntax in C#?

  3. 尝试根据本文来构建您的解决方案:https://www.javaworld.com/article/2073723/why-getter-and-setter-methods-are-evil.html

答案 2 :(得分:0)

问题是为什么您需要这样的东西?为什么不访问对象的属性?一种解决方案可以是来自thomai的上述解决方案。另一种选择是给该方法一个属性选择器作为参数。

Func<Potion, int> valueSelector