【问题标题】:How do I call a string thats displayed within a method into another class?如何将方法中显示的字符串调用到另一个类中?
【发布时间】:2019-10-09 19:36:49
【问题描述】:

我无法将包含字符串的方法显示到不同的类中。

主程序

 Vehicle car = new Vehicle("Toyota", "Camry", 500, "Red", 30, 3, 2);
            car.Display();

车辆

public void Display()
{
    string output = string.Format("MK: {0} MDL: {1} WGT: {2} CLR: {3} MPG: {4} ",
                make, model, weight, color, mpg, tank.GetDisplayString());

    System.Console.WriteLine(output);
}

油箱

public string GetDisplayString()
{
    string output = string.Format("TANK: Cap: {0} LEVEL: {1}", tankCapacity, tankLevel);

    return output;  
}

public void display()
{
    System.Console.WriteLine(GetDisplayString());
}

【问题讨论】:

  • 您能否更详细地描述您所面临的问题?
  • 您没有字符串 tank.GetDisplayString() 的占位符。试试string output = string.Format("MK: {0} MDL: {1} WGT: {2} CLR: {3} MPG: {4} {5}", make, model, weight, color, mpg, tank.GetDisplayString());
  • 您似乎向string.Format 传递了6 个附加参数,但您只使用{0] 到{4} 缺少{5}。
  • @Ruzihm 非常感谢。那将是我尝试过的最后一件事。我肯定让问题变得比它需要的复杂得多。
  • 您能更好地解释问题出在哪种方法上吗?这些变量(品牌、型号、重量、颜色、mpg、tank.GetDisplayString())从何而来?坦克是 GasTank 类型的对象吗?它是如何实例化的?

标签: c# string format-string


【解决方案1】:

你的问题是糟糕的设计。类应该有尽可能少的责任,所以向用户展示自己不应该是其中之一。

另外,在Vehicle.Display 方法中,你不要使用tank.GetDisplayString()

你也有“显示”方法,这是不必要的,即ToString方法,继承自object应该返回你的对象的“字符串表示”,所以你应该覆盖它。

我建议更清洁的方法:

车辆

public override string ToString()
{
    // where tank.ToString() should go? It is not used here...
    return string.Format("MK: {0} MDL: {1} WGT: {2} CLR: {3} MPG: {4} ",
        make, model, weight, color, mpg, tank.ToString());
    // also you can use interpolated string
    // return $"MK: {make} MDL: {model} WGT: {weight} CLR: {color} MPG: {mpg} ";
}

油箱

public override string ToString()
{
    return string.Format("TANK: Cap: {0} LEVEL: {1}", tankCapacity, tankLevel);
}

public void display()
{
   System.Console.WriteLine(GetDisplayString());
}

然后,要显示您的课程,您可以简单地使用:

Console.WriteLine(myVahicle.ToString());
Console.WriteLine(myGasTank.ToString());

【讨论】:

    【解决方案2】:

    string.Format 的格式字符串在您的 Vehicle 类的显示方法中缺少第 5 个参数符号 {5}。要解决此问题,您可以将 {5} 附加到格式字符串:

    string output = string.Format("MK: {0} MDL: {1} WGT: {2} CLR: {3} MPG: {4} {5}",
                    make, model, weight, color, mpg, tank.GetDisplayString());
    

    单独添加:

    string output = string.Format("MK: {0} MDL: {1} WGT: {2} CLR: {3} MPG: {4} ",
                    make, model, weight, color, mpg) + tank.GetDisplayString();
    

    或使用$格式化:

    string output = $"MK: {make} MDL: {model} WGT: {weight} CLR: {color} MPG: {mpg} {tank.GetDisplayString()}"; //This is the same as string.Format just a bit more condensed
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-04
      • 1970-01-01
      • 2013-11-23
      • 2011-04-11
      相关资源
      最近更新 更多