You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让C#的rollFruit方法返回水果名称而非数字?

问题:rollFruit方法返回数字而非水果名称

你当前的核心问题是直接输出了随机生成的索引数字,没有用这个索引去获取fruits列表中对应的水果名称。

修改方式

  1. 先通过randomfruit.Next(0, fruits.Count)生成随机索引并保存;
  2. 用该索引访问fruits列表的元素,再输出这个元素即可。

修正后的完整代码

class DevilFruit // 类名遵循C# PascalCase命名规范
{
    public string Name;
    public int Price;

    public DevilFruit(string name, int price)
    {
        Name = name;
        Price = price;
    }
}

internal class Program
{
    private static void Main(string[] args)
    {
        Console.Title = "Devil Fruit Rolling Text Game";
        Random randomFruit = new Random();
        DevilFruit gomu = new DevilFruit("GomuGomu No Mi", 650000);
        DevilFruit bomu = new DevilFruit("BomuBomu No Mi", 500000);
        DevilFruit bara = new DevilFruit("BaraBara No Mi", 550000);
        DevilFruit sube = new DevilFruit("SubeSube no Mi", 400000);
        DevilFruit kiro = new DevilFruit("KiroKiro no Mi", 440000);
        DevilFruit hana = new DevilFruit("HanaHana no Mi", 700000);
        DevilFruit kage = new DevilFruit("KageKage no Mi", 750000);
        List<string> fruits = new List<string>();

        void RollFruit()
        {
            int randomIndex = randomFruit.Next(0, fruits.Count);
            Console.WriteLine(fruits[randomIndex]); // 通过索引获取并输出水果名称
        }
        
        fruits.Add(gomu.Name);
        fruits.Add(bomu.Name);
        fruits.Add(bara.Name);
        fruits.Add(sube.Name);
        fruits.Add(kiro.Name);
        fruits.Add(hana.Name);
        fruits.Add(kage.Name);
        RollFruit();
    }
}

新手额外建议

  • C#命名规范:类名、方法名、公共成员变量用PascalCase(首字母大写),局部变量用camelCase(首字母小写),能大幅提升代码可读性;
  • 如果后续需要用到水果价格等更多信息,建议直接存储DevilFruit对象到列表(List<DevilFruit> fruits = new List<DevilFruit>()),这样通过随机索引可以获取完整的水果对象,方便扩展功能。

内容的提问来源于stack exchange,提问作者vircobb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 06:15:46