附加依赖属性与字典 - Silverlight
第一篇文章。首先,感谢多年来我从场外学到的所有帮助。我只是有一个相当具体的代码设计问题,我在其他地方找不到。
我有一系列与特定 FrameworkElements 相关的故事板(除其他外),需要在代码中生成,我觉得它要么有点乱,可能有点慢(以为我没有测试过)存储具有 FrameworkElement - Storyboard 关系的字典,以便动态查找。
private static Dictionary<FrameworkElement, Storyboard> storyboardMapping;
private void FrameworkElement_SizeChanged(object sender, SizeChangedEventArgs e)
{
FrameworkElement fe = sender as FrameworkElement;
Storyboard sb = null;
if(storyboardMapping.TryGetValue(fe, out sb))
{
sb.Begin();
}
// etc
}
刚刚考虑使用(私有)附加依赖属性来代替,是否有人对其中一个是否比另一个更快/更干净有意见?我认为使用字典的另一个缺点是它们也不能很好地与弱引用一起使用。作为一名 C# 专家,我不完全理解这是否会导致垃圾收集问题。
另外,我不太确定这本词典能有多大。可能多达 400 个对象甚至更多?
first post. So first off, thanks for all the help over the years as I've learned from the sidelines. I just have a rather specific code-design question that I couldn't find elsewhere.
I have a series of storyboards (among other things,) that relate to specific FrameworkElements, that need to be generated in the code, and I feel that it's either a little messy, and possibly a little slow (thought I haven't tested) to store a dictionary with the FrameworkElement - Storyboard relationships, to lookup on the fly.
private static Dictionary<FrameworkElement, Storyboard> storyboardMapping;
private void FrameworkElement_SizeChanged(object sender, SizeChangedEventArgs e)
{
FrameworkElement fe = sender as FrameworkElement;
Storyboard sb = null;
if(storyboardMapping.TryGetValue(fe, out sb))
{
sb.Begin();
}
// etc
}
Having just considered using (private) Attached Dependency Properties instead, does anyone have an opinion on whether one is faster/cleaner than the other? The other downside I see to using Dictionaries, is that they also don't work well with WeakReferences. Not being a C# Guru, I don't completely understand whether that creates issues with Garbage Collection.
Also, I'm not exactly sure how big this Dictionary could get. Possibly up to 400 objects or even more?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不会担心字典的内存占用。它们只是参考。
但是,存在长期存在的对象(静态)包含对短期存在的对象(UI 元素)的引用的危险,因为这会阻止它们被垃圾收集。
I wouldn't worry about the memory footprint of the dictionary. They are just references.
However, there is a danger of having long lived objects (static) contain references to short lived objects (UI elements) as this keeps them from being garbage collected.
我现在没有使用任何一个,而是使用 UIElements 的
.Resources
属性,这是存储它们的更合适的位置。这个问题之前已经回答过,但答案似乎已经消失了。因此,除非原始答案再次出现,否则我会将这个答案标记为正确的答案...
Rather than using either, I am now using the
.Resources
property of UIElements which is a much more appropriate place to store these.This question was previously answered, however the answer seems to have disappeared. As such I will mark this answer as the correct one unless the original reappears...