我目前正在构建一个应用程序,其中我有一些任务共享一个Dictionary<Object,>
为了避免冲突,实际的字典包含在dictionaryhandler类中,并带有三个方法:
class DictionaryHandler
{
private object lockProcesses = new object();
private Dictionary<Process, Guid> processes = new Dictionary<Process, Guid>();
public Dictionary<Process, Guid> GetProcesses()
{
lock (lockProcesses)
{
// TODO
}
}
public void AddToProcesses(Process process, Guid guid)
{
lock (lockProcesses)
{
processes.Add(process, guid);
}
}
public void RemoveFromProcesses(Process process)
{
lock (lockProcesses)
{
processes.Remove(process);
}
}
}
对于上下文,这是process类:
public class Process
{
public string Name { get; }
public bool Enabled { get; }
public TimeSpan RuntimeWindowStart { get; }
public TimeSpan RuntimeWindowEnd { get; }
public TimeSpan Cooldown { get; }
public int Priority { get; }
public string Username { get; }
public string ExceptionDate { get; }
public string ExceptionDay { get; }
public string AllowedWorkdays { get; }
public string SpecificResource { get; }
public string Assigned { get; set; }
public DateTime? Timestamp { get; set; }
public Process(string name, bool enabled, TimeSpan runtimeWindowStart, TimeSpan runtimeWindowEnd, TimeSpan cooldown, int priority, string username, string exceptionDate, string exceptionDay, string allowedWorkdays, string specificResource, string assigned, DateTime? timestamp)
{
Name = name;
Enabled = enabled;
RuntimeWindowStart = runtimeWindowStart;
RuntimeWindowEnd = runtimeWindowEnd;
Cooldown = cooldown;
Priority = priority;
Username = username;
ExceptionDate = exceptionDate;
ExceptionDay = exceptionDay;
AllowedWorkdays = allowedWorkdays;
SpecificResource = specificResource;
Assigned = assigned;
Timestamp = timestamp;
}
}
我的主要问题是,我想找到一种方法,通过GetProcesses()方法返回字典的副本,而不返回对"实际"的引用。字典。
据我所知,实现这一点的最佳方法是序列化和反序列化字典并返回它。但是我很难做到这一点,因为我找不到一个符合我的情况的例子。
我读了这个和这个,并试图将两者结合起来-不幸的是没有运气。
我的主要问题是,我想找到一种方法,通过GetProcesses()方法返回字典的副本,而不返回对"实际"的引用。字典。
如果你不需要克隆值,你可以使用构造函数重载字典,它接受一个现有的字典:
new Dictionary<Process, Guid>(processes);
如果您确实需要克隆这些值,您可以使用如下命令:
public static Dictionary<Process, Guid> DeepClone<TKey, TValue>(Dictionary<Process, Guid> source)
{
var ret = new Dictionary<Process, Guid>(source.Count, source.Comparer);
foreach (var entry in source)
{
ret.Add(entry.Key, entry.Value);
}
return ret;
}
如果您需要在复制字典时创建Process
类实例的副本,您可以使用:
public class Process
{
// some properties here
public Process ShallowCopy()
{
return (Process) this.MemberwiseClone();
}
}
public static Dictionary<Process, Guid> DeepClone<TKey, TValue>(Dictionary<Process, Guid> source)
{
var ret = new Dictionary<Process, Guid>(source.Count, source.Comparer);
foreach (var entry in source)
{
ret.Add(entry.Key.ShallowCopy(), entry.Value);
}
return ret;
}
用String
代替Guid
Guid是结构类型。因此,序列化和反序列化方法可能无法正常工作。