枚举字符串属性时出现TargetParameterCountException [英] TargetParameterCountException when enumerating through properties of string

查看:37
本文介绍了枚举字符串属性时出现TargetParameterCountException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using the following code to output values of properties:

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 循环内的行上会收到以下错误:

If I run this code for the int, or for the Foo complex type, it works fine. But if I run it for the string (as shown), I get the following error on the line inside the foreach loop:

System.Reflection.TargetParameterCountException:参数计数不匹配.

System.Reflection.TargetParameterCountException: Parameter count mismatch.

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

Does anyone know what this means and how to avoid it?

万一有人问为什么要对字符串的属性进行枚举",最终我希望创建一个通用类,该类将输出传递给它的任何类型的属性(可能是字符串...).

In case anyone asks 'why are you enumerating through the properties of a string', eventually I hope to create a generic class which will output the properties of any type passed to it (which might be a string...).

推荐答案

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

In this case, one of the string's properties is the indexer for returning the character at the specified location. Thus, when you try to GetValue, the method expects an index but doesn't receive one, causing the exception.

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

To check which properties require index you can call GetIndexParameters on the PropertyInfo object. It returns an array of ParameterInfo, but you can just check the length of that array (if there are no parameters, it will be zero)

这篇关于枚举字符串属性时出现TargetParameterCountException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆