Methods.
company.listEmployees[^2].Name = "新しい構文を使用して従業員 2 の名前が変更されました";company.listEmployees[^5].Name = "新しい構文を使用して変更されました Name従業員 5 の名前";company.listEmployees[^8].Name = "新しい構文を使用して従業員 8 の名前が変更されました";Examplepublic class Employee{ public int EmployeeId { get; set; } public string Name { get; set; } public string Gender { get; set; } } public class Company{ public List<Employee> listEmployees; public Company(){ listEmployees = new List<Employee>(); listEmployees.Add(new Employee { EmployeeId = 1, Name = "SS", Gender = "Male" }); listEmployees.Add(new Employee { EmployeeId = 2, Name = "SSS", Gender = "Female" }); listEmployees.Add(new Employee { EmployeeId = 3, Name = "SSSS", Gender = "Male" }); listEmployees.Add(new Employee { EmployeeId = 4, Name = "EE", Gender = "Female" }); listEmployees.Add(new Employee { EmployeeId = 5, Name = "EEEE", Gender = "Female" }); listEmployees.Add(new Employee { EmployeeId = 6, Name = "TTT", Gender = "Male" }); listEmployees.Add(new Employee { EmployeeId = 7, Name = "FFF", Gender = "Male" }); listEmployees.Add(new Employee { EmployeeId = 8, Name = "GGG", Gender = "Male" }); } public string this[int employeeId]{ get{ return listEmployees. FirstOrDefault(x => x.EmployeeId == employeeId).Name; } set{ listEmployees. FirstOrDefault(x => x.EmployeeId == employeeId).Name = value; } } } class Program{ public static void Main(){ Company company = new Company(); Console.WriteLine("Name of Employee with Id = 2: " + company[2]); Console.WriteLine("Name of Employee with Id = 5: " + company[5]); Console.WriteLine("Name of Employee with Id = 8: " + company[8]); System.Console.WriteLine(); Console.WriteLine("Changing names of employees with Id = 2,5,8"); company[2] = "Employee 2 Name Changed"; company[5] = "Employee 5 Name Changed"; company[8] = "Employee 8 Name Changed"; System.Console.WriteLine(); Console.WriteLine("Name of Employee with Id = 2: " + company[2]); Console.WriteLine("Name of Employee with Id = 5: " + company[5]); Console.WriteLine("Name of Employee with Id = 8: " + company[8]); company.listEmployees[^2].Name = "Employee 2 Name Changed using new Syntax"; company.listEmployees[^5].Name = "Employee 5 Name Changed using new Syntax"; company.listEmployees[^8].Name = "Employee 8 Name Changed using new Syntax"; System.Console.WriteLine(); Console.WriteLine("Name of Employee with Id = 2: " + company.listEmployees[^2].Name); Console.WriteLine("Name of Employee with Id = 5: " + company.listEmployees[^5].Name); Console.WriteLine("Name of Employee with Id = 8: " + company.listEmployees[^8].Name); Console.ReadLine(); } }
以上がC# 8.0 でインデクサーを使用するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。