C# 属性属性值的递归迭代转换<>属性



我有下面的方法,我用它迭代类中的所有属性(只是属性(,并在屏幕上打印它们的名称和值(如果有的话(。

public static void PrintProperties(object obj, int indent = 1)
{
if ( obj == null )
return;
string indentString = new string (' ', indent);
Type objType = obj.GetType ();
PropertyInfo[] properties = objType.GetProperties ();
foreach ( PropertyInfo property in properties )
{
object propValue = property.GetValue (obj, null);
var elems = propValue as IList;
if ( elems != null )
{
foreach ( var item in elems )
{
PrintProperties (item, indent + 3);
}
}
else
{
if ( property.PropertyType.Assembly == objType.Assembly )
{
Console.WriteLine("{0}{1}:", indentString, property.Name);
PrintProperties (propValue, indent + 2);
}
else
{
Console.WriteLine("{0}{1}: {2}", indentString, property.Name, propValue);
}
}
}

不幸的是,我将其中一个类中的一个属性从字符串更改为List<string>,以适应必须在其中分配的多个值,现在我出现了错误System.Reflection.TargetParameterCountException: 'Parameter count mismatch.',我不知道如何修复,很可能是因为我有一个List属性。我该如何修复,以便在遇到这样的属性时列出其所有值?有人能帮帮我吗?

您必须做三件事来修复您的实现:

  1. 特别处理字符串(因为否则它们将在实现中被视为char数组(
  2. 特别处理数组(否则会出现异常(
  3. 打印出每个项目的值,而不仅仅是其属性。否则,如果该项目是int,那么它就不会打印出来

沿着这些路线应该可以工作:

public static void PrintProperties(object obj, int indent = 1)
{
if (obj == null)
return;
string indentString = new string(' ', indent);
Type objType    = obj.GetType();
PropertyInfo[] properties = objType.GetProperties();
foreach (PropertyInfo property in properties)
{
object propValue;
if (objType == typeof(string))
return; // Handled at a higher level, so nothing to do here.
if (property.PropertyType.IsArray)
propValue = (Array)property.GetValue(obj);
else
propValue = property.GetValue(obj, null);
var elems = propValue as IList;
if (elems != null)
{
Console.WriteLine("{0}{1}: IList of {2}", indentString, property.Name, propValue.GetType().Name);
for (int i = 0; i < elems.Count; ++i)
{
Console.WriteLine("{0}{1}[{2}] == {3}", indentString, property.Name, i, elems[i]);
if (objType != typeof(string))
PrintProperties(elems[i], indent + 3);
}
}
else
{
if (property.PropertyType.Assembly == objType.Assembly)
{
Console.WriteLine("{0}{1}:", indentString, property.Name);
PrintProperties(propValue, indent + 2);
}
else
{
Console.WriteLine("{0}{1}: {2}", indentString, property.Name, propValue);
}
}
}
}

您可能想要调整输出以适应实际需要,但这应该会为您提供要点。

发生错误的这一行中的问题:

object propValue = property.GetValue (obj, null);

与列表本身无关。试图枚举string上的所有属性是方法的递归性质。如果您只想打印列表的值,一个简单的解决方案是将枚举列表的部分更改为:

var elems = propValue as IList;
if ( elems != null )
{
Console.WriteLine("{0}{1}:", indentString, property.Name);
foreach ( var item in elems )
{
Console.WriteLine("{0}{1}",new string (' ', indent+2),item);
}
}

https://dotnetfiddle.net/NBOA4u

相关内容

最新更新