2015-10-14 104 views
0

我有一个文本框和一个自定义属性是bool的datagridview。我使用反射在运行时启用文本框或datagridview,具体取决于我的自定义属性的设置。代码遍历每个控件的属性,如果它是我的自定义属性和true,那么我启用该控件。C#反射控制属性参数计数不匹配异常

我只在datagridview中出现“参数计数不匹配”异常。我找到了一个解决方法,但我不知道它为什么有效。下面的第一个foreach循环引发异常。第二个不是。

我做了一些搜索,我发现指向属性是索引器的点。我知道它不是和GetIndexParameters()。对于两种控件类型,属性的长度都是0。为什么第一个例子没有工作?

Type type = control.GetType(); 
    PropertyInfo[] properties = type.GetProperties(); 

    //Exception 
    foreach (PropertyInfo property in properties) 
    { 
     if (property.Name == PropName & Convert.ToBoolean(property.GetValue(control, null)) == true) 
      (control as Control).Enabled = true; 
    } 

    //No excpetion 
    foreach (PropertyInfo property in properties) 
    { 
     if (property.Name == PropName) 
      if(Convert.ToBoolean(property.GetValue(control, null)) == true) 
       (control as Control).Enabled = true; 
    } 

回答

1
if (property.Name == PropName & Convert.ToBoolean(property.GetValue(control, null)) == true) 

您正在使用的&代替&&这意味着你正在尝试在执行GetValue财产,不管名称。

在第二个例子中,你只尝试GetValue匹配性质,所以GetValue从未被称为上抛出第一循环异常的财产。

1

您使用了不会短路的单个&。这意味着无论property.Name == PropName的结果如何,它总是会评估第二个操作数,在这种情况下是Convert.ToBoolean(property.GetValue(control, null)) == true声明。

使用双符号&&短路,不会,如果第一个成果,false计算第二个操作数。

相关问题