【问题标题】:TargetParameterCountException when enumerating through properties of string枚举字符串的属性时出现 TargetParameterCountException
【发布时间】:2011-05-27 19:00:20
【问题描述】:

我正在使用以下代码来输出属性值:

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);
}

如果我为intFoo 复杂类型运行此代码,它工作正常。但是如果我为string 运行它(如图所示),我会在foreach 循环内的行中收到以下错误:

System.Reflection.TargetParameterCountException: Parameter count mismatch.

有谁知道这意味着什么以及如何避免它?

如果有人问'为什么要枚举字符串的属性',最终我希望创建一个泛型类,它将输出传递给它的任何类型的属性(可能是字符串......)。

【问题讨论】:

  • 或许问一下如何创建基于反射的属性值枚举器会更有帮助?

标签: c# .net reflection


【解决方案1】:

在这种情况下,字符串的属性之一是用于在指定位置返回字符的索引器。因此,当您尝试GetValue 时,该方法需要一个索引但没有收到一个索引,从而导致异常。

要检查哪些属性需要索引,您可以在 PropertyInfo 对象上调用 GetIndexParameters。它返回一个ParameterInfo的数组,但是你可以只检查那个数组的长度(如果没有参数,它会为零)

【讨论】:

  • 谢谢。如何检测和避免基于索引的属性?
  • 在 PropertyInfo 对象上调用 GetIndexParameters。它返回一个 ParameterInfo 数组,但您可以检查该数组的长度(如果没有参数,它将为零)
【解决方案2】:

System.String 有一个索引属性,它返回指定位置的char。索引属性需要一个参数(在本例中为索引),因此例外。

【讨论】:

    【解决方案3】:

    作为参考...如果您想在读取属性值时避免 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;
            }
        }
    }
    

    希望对你有帮助 ;-)

    【讨论】:

      猜你喜欢
      • 2015-04-14
      • 1970-01-01
      • 1970-01-01
      • 2010-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多