使用反射来实例化对象内的控件属性

时间:2012-06-20 16:02:19

标签: c# .net reflection dynamic instantiation

我在预先存在的代码中测试逻辑,我无法轻易地进行编辑,但代码所在的对象内部有50多个对象,无论出于何种原因这些对象都是null。我要做的是:从我的测试代码,使用反射,遍历我正在测试的类的所有内部对象,如果所述对象为null,则只是实例化它。这就是我到目前为止所做的:

Type ucApprovedType = ucApproved.GetType();
System.Reflection.FieldInfo[] fieldInfo = ucApprovedType.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

foreach (System.Reflection.FieldInfo ucFieldInfo in fieldInfo)
{
    Control control = ucApproved.FindControl(ucFieldInfo.Name);

    if (control == null)
        control = new Control();

    //Set instantiated control back to ucApproved item
}

我遇到的第一个问题是控件从FindControl(ucFieldInfo.Name)调用返回null。然后,一旦我有了instatiated控件,我不知道如何将它的值设置回ucApproved对象,因为我不能执行ucApproved.Controls[0] = control因为ControlCollection是只读的。

1 个答案:

答案 0 :(得分:0)

你几乎就在那里,但它更容易直接使用fieldInfo对象来引用有问题的对象。试试这个:

Type ucApprovedType = ucApproved.GetType();
System.Reflection.FieldInfo[] fieldInfo = ucApprovedType.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

foreach (System.Reflection.FieldInfo ucFieldInfo in fieldInfo)
{
    //get its current value
    Control control = ucFieldInfo.GetValue(ucApproved) as Control;

    if (control == null)
    {
        control = new Control();

        //Set instantiated control back to ucApproved item
        ucFieldInfo.SetValue(ucApproved, control);
    }
}

警告 这真的只有在你在这个循环中获得的ONLY字段是Control字段时才有效。否则,您需要添加过滤器语句。

if (ucFieldInfo.FieldType.IsInstanceOfType(typeof(Control)) || ucFieldInfo.FieldType.IsSubclassOf(typeof(Control)))

或类似。

-------另一种选择-----------

假设ucApproved是一个自定义用户控件,为什么不在控件类中创建一个公共实用程序函数来为您实现控件。

是的,我可以看到你说“不能轻易去编辑”。我甚至理解这个概念。然而,这是一个更容易的答案。调用ucApproved.CreateControls();将是一个更清洁的解决方案。