C# 来自最简单类型的StackOverflowException扩展了DynamicObject
我遇到了一个类型扩展DynamicObject的奇怪问题。我甚至试过MSDN的样品:C# 来自最简单类型的StackOverflowException扩展了DynamicObject,c#,wpf,dynamicobject,C#,Wpf,Dynamicobject,我遇到了一个类型扩展DynamicObject的奇怪问题。我甚至试过MSDN的样品: // The class derived from DynamicObject. public class DynamicDictionary : DynamicObject { // The inner dictionary. Dictionary<string, object> dictionary = new Dictionary<string, obj
// The class derived from DynamicObject.
public class DynamicDictionary : DynamicObject
{
// The inner dictionary.
Dictionary<string, object> dictionary
= new Dictionary<string, object>();
// This property returns the number of elements
// in the inner dictionary.
public int Count
{
get
{
return dictionary.Count;
}
}
// If you try to get a value of a property
// not defined in the class, this method is called.
public override bool TryGetMember(
GetMemberBinder binder, out object result)
{
// Converting the property name to lowercase
// so that property names become case-insensitive.
string name = binder.Name.ToLower();
// If the property name is found in a dictionary,
// set the result parameter to the property value and return true.
// Otherwise, return false.
return dictionary.TryGetValue(name, out result);
}
// If you try to set a value of a property that is
// not defined in the class, this method is called.
public override bool TrySetMember(
SetMemberBinder binder, object value)
{
// Converting the property name to lowercase
// so that property names become case-insensitive.
dictionary[binder.Name.ToLower()] = value;
// You can always add a value to a dictionary,
// so this method always returns true.
return true;
}
}
代码使用一个新的简单控制台,但它只是从一个巨大的WPF应用程序中抛出StackOverflowException。在WPF中,我们有其他使用ExpandooObject的动态代码,但对于DynamicObject它失败了:
WPF项目和控制台都是.NET4.0(完整配置文件)。有人可以分享一些想法吗?您如何在WPF应用程序中使用它?您是否在基于反射的绑定中使用它?你能在WPF应用程序中使用它吗?你能提供一个失败的WPF应用程序示例,使其尽可能简短吗?在普通命令中使用它会绑定到菜单项。我不知道什么是基于反射的绑定,我只是简单地使用上面显示的代码。我还在一个新的WPF项目中进行了尝试,放下一个按钮,在click处理程序上编写代码,效果很好。棘手的是WPF应用程序太大了,所以我不能简单地用一个短的来复制它。你说的“在普通命令中使用它绑定到菜单项”到底是什么意思?你在装订时用它吗?仅仅因为你当前的应用程序很大,并不意味着你不能削减它。复制一份,然后开始销毁它-尽可能多地删除它,这样它就会显示问题。是的,它是一个ICommand对象,并绑定到一个菜单项。动态代码在Execute方法中。我会尽量减少,但这将是一个很大的工作,所以我试图看看是否有人有这个想法。另一件事是,由于应用程序是模块化的,所以实际加载的代码不是很大,但是,环境似乎受到了影响,所以我无法运行它。我没有使用任何花哨的技术,所有东西都是托管代码,所以这真的很奇怪。此外,我还试图追踪堆栈的最开始部分和DLR,看看是什么导致堆栈溢出。
dynamic d = new DynamicDictionary();
d.FirstName = "Jeff"; // stack overflow