反思成本:WPF

时间:2015-06-04 19:13:24

标签: c# reflection

我已经实现了一个扩展帮助程序,可以动态地将WPF用户控件加载到窗口中。 (MyButton在另一个集会中)。

这个助手位于我所有项目中使用的类库中。我们的想法是节省重新编码此操作并保持客户端代码更清洁。

我想第二双眼睛(或更多)让我知道这个成本是否过高。

感谢。

 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;
        }

1 个答案:

答案 0 :(得分:0)

如果您在编译时知道类型,那么制作此通用文件要好得多:

// 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
    };
}

这可能比通过反射找到类型更快,虽然另一种选择是缓存委托来调用无参数构造函数 - 更多的工作,但我的经验更快。您可以通过嵌套泛型类来实现,将类中的Func<T>Func<object>缓存为静态字段。

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

相关问题