【问题标题】:Using reflection to instantiate control properties inside an object使用反射实例化对象内部的控件属性
【发布时间】:2012-06-22 19:48:18
【问题描述】:

我正在测试无法轻松编辑的现有代码中的逻辑,但代码所在的对象内部有 50 多个对象,无论出于何种原因,这些对象都为空。我要做的是:从我的测试代码中,使用反射,遍历我正在测试的类的所有内部对象,如果所述对象为空,则实例化它。这是我迄今为止所拥有的:

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 是只读的。

【问题讨论】:

    标签: c# .net reflection dynamic instantiation


    【解决方案1】:

    您快到了,但直接使用 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);
        }
    }
    

    警告 如果您在此循环中获得的唯一字段是Control 字段,这实际上只适用。否则需要添加过滤语句。

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

    或类似的。

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

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

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

    【讨论】:

    • 这很棒! (符合不同类型的控件)非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-05
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    • 2013-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多