【问题标题】:How to reference a variable in method parameter?如何在方法参数中引用变量?
【发布时间】:2019-11-17 14:06:41
【问题描述】:

对不起,如果标题不准确,我真的不知道我要查找的内容的名称

假设我有这个类:

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

本质上我怎样才能让一个参数(selectedliquid)引用一个类中的不同变量(水量或试剂量)?

或者这是不可能的,我确实需要为每个要检查的变量使用 1 种方法?

【问题讨论】:

    标签: c# unity3d methods parameters


    【解决方案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);
    }
    

    【讨论】:

      【解决方案2】:

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

      更好的是真正有两种方法可以得到你想要的变量。但是您需要重新考虑是否需要这些 getter,或者您希望班级为您做其他事情。看看这是否是一个选项: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

      【讨论】:

        【解决方案3】:

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

        Func<Potion, int> valueSelector

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-05-12
          • 2022-01-15
          • 1970-01-01
          相关资源
          最近更新 更多