gpt4 book ai didi

c# - 在控制离开当前方法之前必须分配 out 参数

转载 作者:太空狗 更新时间:2023-10-30 00:30:17 29 4
gpt4 key购买 nike

我是 C# 的新手,这是我第一次对列表做任何事情,所以这可能是一个非常愚蠢的问题......我正在尝试将数据从文件读取到包含以下内容的列表Tourist 对象。据我所知,在向列表添加对象之前,我需要为 tourists 列表分配一些内容,但我不确定该怎么做。

class Tourist
{
public string FirstName { get; set; }
public string LastName { get; set; }
public double Contributed { get; set; }

public Tourist(string firstName, string lastName, double money)
{
FirstName = firstName;
LastName = lastName;
Contributed = money * 0.25;
}
}

class Program
{
static void Main(string[] args)
{
List<Tourist> tourists = new List<Tourist>();

ReadData(out tourists);
}

static void ReadData(out List<Tourist> tourists)
{
const string Input = "..\\..\\Duomenys.txt";

string[] lines = File.ReadAllLines(Input);
foreach (string line in lines)
{
string[] values = line.Split(';');
string firstName = values[0];
string lastName = values[1];
double money = Double.Parse(values[2]);
tourists.Add(new Tourist(firstName, lastName, money));
}
}
}

最佳答案

通过将参数声明为 out,您“ promise ”调用者(和编译器)您的方法将为作为该参数参数提供的变量设置一个值 .

因为您 promise ,通过您的方法的每条路径都必须为此参数分配一个值。

您的方法不会tourists 赋值。如果使用 null 引用调用该方法,这实际上可能会导致 tourists.Add(...) 处的 NullReferenceException

对我来说,您似乎可以在初始化 Main 中的 tourists 时省略 out 关键字。 请注意 ReadData 只会修改列表的内容,而不是对它的引用 存储在游客 变量。由于您不想更改该引用(变量的值),因此您不需要 out 关键字。

如果你想让ReadData初始化它,你需要添加这行

tourists = new List<Tourist>()

ReadData foreach 循环之前。


就您的代码而言,更好的解决方案是将任何参数省略到 ReadData 并让方法返回 列表:

static List<Tourist> ReadData()
{
// create list
List<Tourist> tourists = new List<Tourist>();

const string Input = "..\\..\\Duomenys.txt";

string[] lines = File.ReadAllLines(Input);
foreach (string line in lines)
{
// shortened for brevity
tourists.Add(new Tourist(firstName, lastName, money));
}

return tourists; // return newly created list
}

然后在 Main 中使用它,例如:

static void Main(string[] args)
{
List<Tourist> tourists = ReadData();
}

关于c# - 在控制离开当前方法之前必须分配 out 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39469756/

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