我想知道初始化列表对象时出了什么问题。我们不能在同一个类中创建列表对象。初始化列表对象的规则集是什么?
class Program
{
static void Main(string[] args)
{
public int ID { get; set; }
public string Name { get; set; }
public int Salary { get; set; }
List<Program> emloyeelist = new List<Program>();
emloyeelist.Add(new Program() { ID = 1, Name = "Seema", Salary = 10000 });
**// error shown for "employeelist" in employee.Add stating that "field used like type"**
emloyeelist.Add(new Program() { ID = 2, Name = "Arun", Salary = 20000 });
emloyeelist.Add(new Program() { ID = 3, Name = "Nayana", Salary = 30000 });
emloyeelist.Add(new Program() { ID = 4, Name = "Nayana", Salary = 12000 });
emloyeelist.Add(new Program() { ID = 5, Name = "Raman", Salary = 55000 });
foreach (Program emp in emloyeelist)
{
if (emp.Salary > 20000)
{
Console.WriteLine(emp.Name +" "+"\t"+"has salry"+"\t"+ " " + emp.Salary);
}
}
}
}
答案 0 :(得分:2)
将方法外的属性移动到单独的Employee类:
class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public int Salary { get; set; }
}
class Program
{
static void Main(string[] args) {
List<Employee> emloyeelist = new List<Employee>();
emloyeelist.Add(new Employee() { ID = 1, Name = "Seema", Salary = 10000 });
emloyeelist.Add(new Employee() { ID = 2, Name = "Arun", Salary = 20000 });
emloyeelist.Add(new Employee() { ID = 3, Name = "Nayana", Salary = 30000 });
emloyeelist.Add(new Employee() { ID = 4, Name = "Nayana", Salary = 12000 });
emloyeelist.Add(new Employee() { ID = 5, Name = "Raman", Salary = 55000 });
foreach (Employee emp in emloyeelist)
{
if (emp.Salary > 20000)
{
Console.WriteLine(emp.Name +" "+"\t"+"has salry"+"\t"+ " " + emp.Salary);
}
}
}
}
答案 1 :(得分:1)
您需要定义List<T>
可以使用的自定义类。试试这样:
public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public decimal Salary { get; set; }
}
在此之后使用您的列表:
List<Employee> EmpList = new List<Employee>();
/*Add your data to the list */
foreach (Employee emp in emloyeelist)
{
if (emp.Salary > 20000)
{
Console.WriteLine(emp.Name +" "+"\t"+"has salry"+"\t"+ " " + emp.Salary);
}
}
这样,您可以将所需数据包装在自定义对象中,该对象仅用于包含此数据。你不需要强奸program
课程。