通过字符串属性枚举时的TargetParameterCountException

| 我正在使用以下代码输出属性值:
string output = String.Empty;
string stringy = \"stringy\";
int inty = 4;
Foo spong = new Foo() {Name = \"spong\", NumberOfHams = 8};
foreach (PropertyInfo propertyInfo in stringy.GetType().GetProperties())
{
  if (propertyInfo.CanRead) output += propertyInfo.GetValue(stringy, null);
}
如果我为
int
Foo
复杂类型运行此代码,则可以正常工作。但是,如果我为
string
运行它(如图所示),则在
foreach
循环内的行上会收到以下错误: System.Reflection.TargetParameterCountException:参数计数不匹配。 有谁知道这意味着什么以及如何避免呢? 万一有人问“为什么要枚举字符串的属性”,最终我希望创建一个通用类,该类将输出传递给它的任何类型的属性(可能是字符串...)。     
已邀请:
        在这种情况下,字符串的属性之一是用于在指定位置返回字符的索引器。因此,当您尝试将值设置为“ 5”时,该方法需要一个索引,但不会收到索引,从而导致异常。 要检查哪些属性需要索引,可以在
PropertyInfo
对象上调用
GetIndexParameters
。它返回一个
ParameterInfo
数组,但是您只需检查该数组的长度即可(如果没有参数,则为零)。     
        
System.String
具有一个索引属性,该属性在指定位置返回returns10。有索引的属性需要一个参数(在这种情况下为索引),因此需要例外。     
        只是作为参考...如果在读取属性值时要避免TargetParameterCountException:
// Ask each childs to notify also, if any could (if possible)
foreach (PropertyInfo prop in options.GetType().GetProperties())
{
    if (prop.CanRead) // Does the property has a \"Get\" accessor
    {
        if (prop.GetIndexParameters().Length == 0) // Ensure that the property does not requires any parameter
        {
            var notify = prop.GetValue(options) as INotifyPropertyChanged; 
            if (notify != null)
            {
                notify.PropertyChanged += options.OptionsBasePropertyChanged;
            }
        }
        else
        {
            // Will get TargetParameterCountException if query:
            // var notify = prop.GetValue(options) as INotifyPropertyChanged;
        }
    }
}
希望能帮助到你 ;-)     

要回复问题请先登录注册