【发布时间】: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);
}
如果我为int 或Foo 复杂类型运行此代码,它工作正常。但是如果我为string 运行它(如图所示),我会在foreach 循环内的行中收到以下错误:
System.Reflection.TargetParameterCountException: Parameter count mismatch.
有谁知道这意味着什么以及如何避免它?
如果有人问'为什么要枚举字符串的属性',最终我希望创建一个泛型类,它将输出传递给它的任何类型的属性(可能是字符串......)。
【问题讨论】:
-
或许问一下如何创建基于反射的属性值枚举器会更有帮助?
标签: c# .net reflection