如何在 C# VS 中使用 list<> 方法

  • 本文关键字:list 方法 VS c#
  • 更新时间 :
  • 英文 :


我有一个关于c#中列表的问题。

public void example(Employee emp)

现在我需要写

example();

在另一个方法

但是当我这样做时,它显示了一个错误,因为我需要在()中放入一些东西,但我不知道是什么或如何。谢谢!


public void SaveToFile(Employee emp)
{

var path2 = Path.Combine(Directory.GetCurrentDirectory(), "text.txt");
File.AppendAllText(path2, emp2 + Environment.NewLine);
}
//ABOVE ME IS THE METHOD I WANNA CALL
//BELOW IS THE START PROGRAM THING (employeedata is another script)
private static void MainMenu(ref EmployeeData employeeData)
{
employeeData.SaveToFile(Employee emp);
}

在所有的注释之后,我猜这就是你需要的:你必须在调用void时在参数中传递一个employee对象。

Employeee emp = new Employee();
emp.propertyOne = "stuff";
emp.propertyTwo = "more stuff";
example(emp);

您需要传递之间的一个值()的参数,因为在你的方法你要求一个对象类型的员工。请查看以下url,您可以了解更多关于参数的信息:

c#中的参数

你思念是一种Employee对象转换成string写入到一个文件中。

使用.ToString()覆盖。
public class Employee
{
public Employee()
{
// Constructor defaults
ID = 0;
Name = string.Empty;
}
public bool IsValid
{
get
{
// Check if ID and Name are set
return ID > 0 && !string.IsNullOrWhiteSpace(Name);
}
}
public int ID { get; set; }
public string Name { get; set; }
public override string ToString()
{
// String representation of an Employee
return $"{ID}, {Name}";
}
}

然后你可以编写代码来读写文件

public static class EmployeeData 
{
public static void AppendToFile(string filename, Employee employee)
{
// Use `ToString()` to convert `Employee` to `string`
File.AppendAllText(filename, employee.ToString() + Environment.NewLine);
}
public static Employee Parse(string description)
{
// Take a string of the form "100, John" and split it
// into parts at the comma
string[] parts = description.Trim().Split(',');
Employee emp = new Employee();
if (parts.Length > 0 && int.TryParse(parts[0].Trim(), out int id))
{
// If first part is an integer, assign it to the ID
emp.ID = id;
}
if (parts.Length > 1)
{
// Assign second part to name
emp.Name = parts[1];
}
return emp;
}
public static List<Employee> ReadFromFile(string filename)
{
// Read all text from file as separate lines
List<Employee> list = new List<Employee>();
string[] lines = File.ReadAllLines(filename, Encoding.UTF8);
foreach (var line in lines)
{
// Convert each line of text into an Employee object
Employee emp = Parse(line);
if (emp.IsValid)
{
// If the object is valid add to the list
list.Add(emp);
}
}
return list;
}
}

和上面的代码用于下面的概念证明代码:

internal class Program
{
static void Main(string[] args)
{
Employee emp1 = new Employee()
{
ID = 1,
Name = "Peter",
};
EmployeeData.AppendToFile("test.txt", emp1);
Employee emp2 = new Employee()
{
ID  = 2,
Name = "Maria",
};
EmployeeData.AppendToFile("test.txt", emp2);
List<Employee> employees = EmployeeData.ReadFromFile("test.txt");
foreach (var item in employees)
{
Console.WriteLine(item);
// This calls item.ToString()
}
}
}

,它在第一次运行

时在控制台窗口上打印以下内容
1,  Peter
2,  Maria

请注意,每次程序运行时,它都会向上面添加创建副本。这是另一个问题的主题,关于如何编写.Equals()函数来检查重复。

最新更新