如何访问由反射C#创建的表单变量

How to access to form variables created by reflection c#

大家好,我正在尝试设置这样创建的表单变量

var type = Type.GetType("namespace." + "formName");
Form form = Activator.CreateInstance(type) as Form;

变量是在表单设计器中创建的

public int myVariable = 0;

我大概想让它做的是 form.variable = 7 我试过这个:

form.GetType().GetProperty(propertyName).SetValue(form, 7, null);

但是它不起作用:(

编辑 对不起大家,如果我没有解释清楚,我会尝试更具体

        private void ShowForm(string frmname, string propertyName, int propertyValue)
    {
        var type = Type.GetType("RetailSystem.Compras." + frmname);
        Form form = Activator.CreateInstance(type) as Form;

        if (form != null)
        {
            // Set variables
            form.Show();
        }            
    }

此函数将接收一个字符串,它是表单的名称

为了清楚起见,让我们把它放到一个答案中。 拥有实例后,它几乎就是一个常规对象;您不需要继续使用反射来改变它的状态。即,正如 Olivier 所建议的那样:form.myVariable = 7; 应该就可以了。 此外,如果您需要通过反射更改值,该图标表明 idAnalisisComprasfield, not a property, so you'd have to use GetField

form.GetType().GetField(propertyName).SetValue(form, 7, null);

查看您的编辑,您似乎想要一个函数来实例化一个表单并将给定的 property/field 设置为一个值。如果您事先不知道是否会收到 属性 或要设置的字段,则必须检查 GetProperty returns 是否为空,然后转到 GetField。您可以通过 null coalescing 结果来做到这一点。

private void ShowForm(string frmname, string propertyName, int propertyValue)
{
    var type = Type.GetType("RetailSystem.Compras." + frmname);
    Form form = Activator.CreateInstance(type) as Form;

    if (form != null)
    {
        var PropOrField = form.GetType().GetProperty(propertyName) 
             ?? form.GetType().GetField(propertyName);
        if(PropOrField is null)
        {
          //propertyName isn't a property nor a field on your form.
        }
        form.Show();
    }            
}

这一切都非常糟糕,似乎指向更深层次的设计问题。