首页 > 解决方案 > 如何在 C# 中动态获取 LIST<> 中的多个字段的用户输入,而不是像我在下面的代码中那样进行硬编码?

问题描述

using System;
using System.Collections.Generic;

namespace Branches
{
    public class Branch
    {
        public int Id { get; set; }
        public string Code { get; set; }
        public string Name { get; set; }  

        public Branch() { }

        public Branch(int id, string code, string name)
        {
            Id = id;
            Code = code;
            Name = name;
        }
    }

    class Program
    {
        static void Main()
        {
            List<Branch> br = new List<Branch>(){
                new Branch(){ Id=401, Code="SBI120800", Name="Chembur West" },
                new Branch(){ Id=402, Code="SBI120700", Name="Chembur East" },
                new Branch(){ Id=403, Code="SBI120900", Name="Govandi West" },
                new Branch(){ Id=404, Code="SBI120500", Name="Govandi East" },
                new Branch(){ Id=405, Code="SBI120400", Name="Andheri West" },
                new Branch(){ Id=406, Code="SBI120300", Name="Andheri East" },
            };

            foreach (var branches  in br)
            {
                Console.WriteLine(branches.Name);
            }
        }
    }
}

标签: c#.netlistinputdynamic

解决方案


你可以这样做:

List<Branch> br = new List<Branch>();
while(true) 
{
 Console.WriteLine("Please provide Id")
 var id =  Console.ReadLine();
 ... // Ask other questions 
 br.Add( new Branch { Id =id, ...});
 Console.WriteLine("Would you like to add another branch? Y/N");
 if(Console.ReadKey().ToLower() == 'n') break;
}

推荐阅读