我想知道如何访问ListArray 1并打印添加到该ListArray的对象的参数之一
主程序:
namespace ConsoleApp1 {
class Program
{
static void Main(string[] args)
{
UserDetails ud = new UserDetails();
List<TaskDetails> taskDetails = new List<TaskDetails>();
Console.Write("Please enter User ID: ");
string i = Console.ReadLine();
Console.Write("Please enter username: ");
string s = Console.ReadLine();
ud.SetDetails(i, s);
int cnt = int.Parse(Console.ReadLine());
for (int x=1; x <= cnt; x++)
{
Console.Write("Please enter title for Task: " + x + " ");
string title = Console.ReadLine();
TaskDetails td = new TaskDetails();
td.SetTask(i, title);
taskDetails.Add(td);
}
PrintDetails pd = new PrintDetails();
}
}
}
任务详细信息
namespace ConsoleApp1
{
class TaskDetails
{
private string UserID { set; get; }
private string TaskTitle { set; get; }
private List<TaskDetails> TaskList = new List<TaskDetails>();
public TaskDetails() { }
public List<TaskDetails> GetTaskList
{
get { return TaskList; }
}
public void SetTask(string userID, string taskTitle)
{
this.UserID = userID;
this.TaskTitle = taskTitle;
}
}
}
这是我用于访问TaskDetails类中ArrayList的类,我希望能够通过索引及其参数之一来访问数组中的对象
namespace ConsoleApp1
{
class PrintDetails
{
public void print(int i)
{
TaskDetails qw = new TaskDetails();
List<TaskDetails> MyList1 = qw.GetTaskList;
Console.WriteLine(qw.GetTaskList);
}
}
}
答案 0 :(得分:1)
因此,我认为您面临的问题是,当您创建新的TaskDetails时,会初始化TaskDetails的新版本,该版本开始为空。如果您认为PrintDetails需要一个单独的类,则可以使用以下内容:
namespace ConsoleApp1
{
class PrintDetails
{
public void Print(List<TaskDetails> taskDetails, int i)
{
var taskDetail = taskDetails[i];
Console.WriteLine(string.Format(
"UserID: {0}, TaskTitle: {1}",
taskDetail.UserID,
taskDetail.TaskTitle);
}
}
}
然后在您的主函数中,按以下方式调用它:
PrintDetails pd = new PrintDetails();
pd.Print(taskDetails, i);