You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何使用循环计数变量命名C# Record实例?若不可行请提供替代方案

如何用循环计数变量管理Record实例并实现遍历?

嘿,我看你想通过循环计数变量i来命名每个products实例,同时记录总数量并能遍历所有实例——这个需求的核心其实是存储多个实例并方便访问,但你当前的代码实现有几个关键问题:

  • C#里的变量名是静态标识符,没法用动态的数值i生成类似i1i2这样的变量名,这种动态命名变量的思路在C#里是行不通的
  • 你代码里products i = new(...)这行把i定义成了products类型的实例,后面又写i = i + 1,这完全不符合类型逻辑:products默认没有定义+运算符,而且你实际想做的是让计数器加1,不是修改实例本身

替代解决方案:用集合存储实例

最适合你的方案是用集合类型(比如List<products>)来存储所有创建的实例,这样既可以轻松获取总数量,也能通过for/foreach遍历每一个实例。

下面是修改后的完整代码(我补充了products的Record定义,同时优化了输入验证):

// 先定义你的products Record(如果还没定义的话)
public record products(string Name, float ValueInPounds);

// 主逻辑部分
List<products> productCollection = new List<products>();
string userInput = string.Empty;

while (userInput != "none")
{
    Console.WriteLine("Input a product Name or type \"none\" to exit.");
    userInput = Console.ReadLine();
    
    if (userInput == "none")
        break;

    Console.WriteLine("Input this product's value in Pounds.");
    // 用TryParse处理无效输入,避免程序崩溃
    if (float.TryParse(Console.ReadLine(), out float productValue))
    {
        // 将新创建的实例添加到集合中
        productCollection.Add(new products(userInput, productValue));
    }
    else
    {
        Console.WriteLine("Invalid number format, please try again.");
    }
}

// 获取总数量(直接用集合的Count属性)
int totalProductCount = productCollection.Count;
Console.WriteLine($"\nTotal products added: {totalProductCount}");

// 用foreach遍历所有实例(最简洁的方式)
Console.WriteLine("\nAll products:");
foreach (var product in productCollection)
{
    Console.WriteLine($"Name: {product.Name}, Value: {product.ValueInPounds} lbs");
}

// 如果你想用计数变量i来遍历,用for循环即可
Console.WriteLine("\nIterating with index i:");
for (int i = 0; i < productCollection.Count; i++)
{
    var currentProduct = productCollection[i];
    Console.WriteLine($"Product {i + 1}: Name={currentProduct.Name}, Value={currentProduct.ValueInPounds} lbs");
}

代码说明

  • List<products>存储所有实例,完美解决了“动态命名变量”的问题,所有实例都在一个集合里统一管理
  • 添加了float.TryParse来处理用户输入的非数值内容,让程序更健壮
  • 总数量直接通过productCollection.Count获取,不需要额外维护计数器(如果一定要用计数器,也可以在循环里声明int i = 0;,每次添加实例后i++,效果一致)
  • 遍历方式灵活:既可以用foreach直接遍历实例,也可以用for循环结合索引i来访问,满足你想用i遍历的需求

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

火山引擎 最新活动