gpt4 book ai didi

C# 使用字符串中的名称创建一个对象的多个实例

转载 作者:太空宇宙 更新时间:2023-11-03 23:12:45 24 4
gpt4 key购买 nike

我正在尝试从 .txt 文件加载一些信息,然后创建一个类的实例...我需要为 .txt 文件中的每一行创建一个新实例,我想按顺序命名每个实例。 .txt 文件中的第一行将创建名为 card1 的实例,另一行将创建名为 card2 的实例....txt 文件中确实有很多行,因此我需要将此过程自动化,但这就是我所做的不起作用,因为我似乎不能使用字符串作为实例的名称......有什么可以解决这个问题的吗?感谢您的帮助...

Console.WriteLine("Loading cards from .txt file");
using (StreamReader sr = new StreamReader(@"G:\Temp\cards.txt"))
{
string s;
int cardIndex = 1;
while ((s = sr.ReadLine()) != null)
{
string cardName = "card" + cardIndex.ToString();
Card cardName = new Card(s)
cardIndex++;
}
}

最佳答案

您的问题是您对 Cardstring 变量使用了相同的名称。

Console.WriteLine("Loading cards from .txt file");
using (StreamReader sr = new StreamReader(@"G:\Temp\cards.txt"))
{
string s;
int cardIndex = 1;
Dictionary<string, Card> d = new Dictionary<string, Card>();

while ((s = sr.ReadLine()) != null)
{
string cardName = "card" + cardIndex.ToString();
Card card = new Card(cardName, s);
d.Add(s, card);

cardIndex++;
}
}

然后您可以根据您拥有的构造函数/类的实现将cardNames 和任何您想要的card 传递给card

要访问它,请使用您喜欢的任何一种访问字典中值的方式:通过 []TryGet 就像其他指定的那样。


虽然这会解决您的问题,但我建议对代码进行相当多的重构。如果您处于那个级别并且了解正在发生的事情,我会采用@Dmitry 建议的方式(使用 linq)。

这是一种拥有索引并为每个创建这些对象的好而优雅的方式 - 来 self 的支持

关于C# 使用字符串中的名称创建一个对象的多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38479939/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com