Обращение к структуре через индексатор и изменение её поля - C#
Формулировка задачи:
Возможно ли в C#?
class SomeClass
{
// Хочу вот так
void Test()
{
this["Desu"].Version = 10;
}
struct Client
{
public Client(string Name, string Folder, int Version, int LastVersion = 0)
{
this.Name = Name;
this.Folder = Folder;
this.Version = Version;
this.LastVersion = LastVersion;
}
public string Name;
public string Folder;
public int Version;
public int LastVersion;
}
public Client this[string Name]
{
get
{
foreach (Client cl in Clients)
if (cl.Name == Name)
return cl;
}
set
{
// ?
}
}
Client[] Clients;
}Решение задачи: «Обращение к структуре через индексатор и изменение её поля»
textual
Листинг программы
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var clients = new Client[]
{
new Client("Вася", "", 0, -1),
new Client("Петя", "", 1, -1),
new Client("Сидор", "", 2, -1),
new Client("Иван", "", 0, 0),
new Client("Петя2", "", 5, 2),
};
ClientManager manager = new ClientManager();
foreach (var item in clients)
manager[item.Name] = item;
manager["Вася"].Version = 34;
Console.WriteLine(manager["Вася"].Version);
Console.ReadKey(true);
}
}
public class Client
{
public Client(string Name, string Folder, int Version, int LastVersion = 0)
{
this.Name = Name;
this.Folder = Folder;
this.Version = Version;
this.LastVersion = LastVersion;
}
public string Name;
public string Folder;
public int Version;
public int LastVersion;
}
public class ClientManager
{
Dictionary<string, Client> list = new Dictionary<string, Client>();
public Client this[string Name]
{
get
{
Client result;
if (list.TryGetValue(Name, out result))
return result;
else
throw new ArgumentOutOfRangeException("Элемента с указанным ключом не существует.");
}
set
{
if (list.ContainsKey(Name)) list.Remove(Name);
list.Add(Name, value);
}
}
}
}