反射成本:WPF

Cost of reflection: WPF

我已经实现了一个扩展助手来动态地将 WPF 用户控件加载到 window。 (MyButton 在另一个程序集中)。

这个助手在我所有项目中使用的 class 库中。这个想法是为了节省重新编码此操作并保持客户端代码更清晰。

我希望有第二双(或更多)眼睛告诉我这样做的成本是否太高。

谢谢。

 public static Window OpenUserControl(this MyButton button, string controlName, string title)
        {
            //      
            object uControl;
            try
            {
                Type newType = button.GetType().Assembly.GetType(controlName,true,true);
                uControl = Activator.CreateInstance(newType);
            }
            catch (Exception e)
            {                
                throw;
            }


            // launch the usercontrol as a window.
            Window form = new Window
            {
                Title = title,
                Content = uControl,
                ShowInTaskbar = false
            };
            return form;
        }

如果您在编译时知道类型,那么将其设为泛型会好很多:

// Possibly add more generic constraints to T?
public static Window OpenUserControl<T>(string title)
    where T : new()
{
    return new Window
    {
        Title = title,
        Content = new T(),
        ShowInTaskbar = false
    };
}

这可能比通过反射查找类型快 ,尽管另一种选择是缓存委托以调用无参数构造函数 - 工作量更大,但效果更佳根据我的经验更快。您可以通过嵌套的泛型 class 来做到这一点,将 Func<T>Func<object> 作为静态字段缓存在 class 中。

只有您才能真正判断这是否足够快 - 但它应该很容易进行基准测试,我非常怀疑它是否会成为瓶颈。