这适用于基于MVVM的WPF项目:
我在视图模型中使用ExpandoObject
作为对话框,它非常好用,因为它实现了INotifyPropertyChanged
,我可以直接在XAML中绑定到对象的属性。
但是,为了说明用户操纵数据然后点击取消,我需要复制ExpandoObject
以恢复原始内容。
在对话框中,没有属性添加到对象中。
如何克隆它?
答案 0 :(得分:9)
作为静态打字的忠实信徒,eugh ......
话虽如此,看起来ExpandoObject
实现了IDictionary<string, object>
:
dynamic foo1d = new ExpandoObject();
foo1d.a = "test";
dynamic foo2d = new ExpandoObject();
foreach (var kvp in (IDictionary<string, object>)foo1d)
{
((IDictionary<string, object>)foo2d).Add(kvp);
}
Debug.Assert(foo1d.a == foo2d.a);
或在VB中:
Dim foo1d As Object = New ExpandoObject
Dim foo2d As Object = New ExpandoObject
foo1d.a = "foo"
Dim cloneDictionary = CType(foo2d, IDictionary(Of String, Object))
For Each line In CType(foo1d, IDictionary(Of String, Object))
cloneDictionary.Add(line.Key, line.Value)
Next
我会注意到这只是一个浅层克隆。你必须做进一步的工作来克隆引用的对象。
答案 1 :(得分:4)
浅拷贝:
static ExpandoObject ShallowCopy(ExpandoObject original)
{
var clone = new ExpandoObject();
var _original = (IDictionary<string, object>)original;
var _clone = (IDictionary<string, object>)clone;
foreach (var kvp in _original)
_clone.Add(kvp);
return clone;
}
深拷贝:
static ExpandoObject DeepCopy(ExpandoObject original)
{
var clone = new ExpandoObject();
var _original = (IDictionary<string, object>)original;
var _clone = (IDictionary<string, object>)clone;
foreach (var kvp in _original)
_clone.Add(kvp.Key, kvp.Value is ExpandoObject ? DeepCopy((ExpandoObject)kvp.Value) : kvp.Value);
return clone;
}
答案 2 :(得分:-2)
a = ["Hello, how are you", "Hello, I'm well", "What is your name"]
a.group_by{|e| e[0, 3]}
只要url是动态对象的属性,这就行了。
如果您正在使用没有具体类型并且您想要修改/排序结果的服务调用,那么它非常有用。