我有一个通用字典dictionary <string, T>,我想基本上使克隆()..任何建议。
当前回答
(注意:虽然克隆版本可能很有用,但对于简单的浅复制,我在另一篇文章中提到的构造函数是更好的选择。)
你希望拷贝的深度是多少,你使用的是什么版本的。net ?如果你使用的是。net 3.5,我认为对ToDictionary的LINQ调用,同时指定键和元素选择器将是最简单的方法。
例如,如果你不介意这个值是一个浅克隆:
var newDictionary = oldDictionary.ToDictionary(entry => entry.Key,
entry => entry.Value);
如果你已经限制了T来实现ICloneable:
var newDictionary = oldDictionary.ToDictionary(entry => entry.Key,
entry => (T) entry.Value.Clone());
(这些方法未经测试,但应该有效。)
其他回答
对于。net 2.0,你可以实现一个继承自Dictionary并实现ICloneable的类。
public class CloneableDictionary<TKey, TValue> : Dictionary<TKey, TValue> where TValue : ICloneable
{
public IDictionary<TKey, TValue> Clone()
{
CloneableDictionary<TKey, TValue> clone = new CloneableDictionary<TKey, TValue>();
foreach (KeyValuePair<TKey, TValue> pair in this)
{
clone.Add(pair.Key, (TValue)pair.Value.Clone());
}
return clone;
}
}
然后,只需调用clone方法就可以克隆字典。当然,这个实现要求字典的值类型实现ICloneable,但除此之外,泛型实现根本不实用。
这对我来说很好
// assuming this fills the List
List<Dictionary<string, string>> obj = this.getData();
List<Dictionary<string, string>> objCopy = new List<Dictionary<string, string>>(obj);
正如Tomer Wolberg在评论中所描述的,如果值类型是可变类,这是行不通的。
(注意:虽然克隆版本可能很有用,但对于简单的浅复制,我在另一篇文章中提到的构造函数是更好的选择。)
你希望拷贝的深度是多少,你使用的是什么版本的。net ?如果你使用的是。net 3.5,我认为对ToDictionary的LINQ调用,同时指定键和元素选择器将是最简单的方法。
例如,如果你不介意这个值是一个浅克隆:
var newDictionary = oldDictionary.ToDictionary(entry => entry.Key,
entry => entry.Value);
如果你已经限制了T来实现ICloneable:
var newDictionary = oldDictionary.ToDictionary(entry => entry.Key,
entry => (T) entry.Value.Clone());
(这些方法未经测试,但应该有效。)
Dictionary<string, int> dictionary = new Dictionary<string, int>();
Dictionary<string, int> copy = new Dictionary<string, int>(dictionary);
在这种情况下,你有一个"object"的字典,object可以是(double, int,…或ComplexClass):
Dictionary<string, object> dictSrc { get; set; }
public class ComplexClass : ICloneable
{
private Point3D ...;
private Vector3D ....;
[...]
public object Clone()
{
ComplexClass clone = new ComplexClass();
clone = (ComplexClass)this.MemberwiseClone();
return clone;
}
}
dictSrc["toto"] = new ComplexClass()
dictSrc["tata"] = 12.3
...
dictDest = dictSrc.ToDictionary(entry => entry.Key,
entry => ((entry.Value is ICloneable) ? (entry.Value as ICloneable).Clone() : entry.Value) );
推荐文章
- 如何在c#中获得正确的时间戳
- Linq选择列表中存在的对象(A,B,C)
- c# .NET中的App.config是什么?如何使用它?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 更好的方法将对象转换为int类型
- 我可以将c#字符串值转换为转义字符串文字吗?
- 在c#中转换char到int
- c#中朋友的对等物是什么?
- 关键字使用virtual+override vs. new
- 在ASP中选择Tag Helper。NET Core MVC
- 如何在没有任何错误或警告的情况下找到构建失败的原因
- 跨线程操作无效:控件“textBox1”从创建它的线程以外的线程访问
- 否ConcurrentList<T>在。net 4.0?
- 在c#中解析字符串为日期时间