オブジェクトを渡すことができる一般的な関数を作成しようとしています。これにより、c#のすべてのプロパティと値が出力されます。
私はこのような多くの例を試しましたが、他のいくつかの例は
public void PrintProperties(object obj)
{
PrintProperties(obj, 0);
}
public void PrintProperties(object obj, int indent)
{
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);
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);
}
}
}
と
foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(obj))
{
string name = descriptor.Name;
object value = descriptor.GetValue(obj);
Console.WriteLine("{0}={1}", name, value);
}
しかし、デバッグ/ログファイルに必要なオブジェクトのいくつかには、string[]プロパティが含まれています。これらの例はすべて、これらを次のように出力します
System.String[]
私が次のようなオブジェクトを持っていた場合
class Thing
{
public string Name { get; set; }
public int Number { get; set; }
public string[] Names { get; set; }
}
設定された値が何であれ、次のようにログに表示されると思います
Name: Test
Number: 3
Names[0]: Fred
Names[1]: John
Names[2]: Jimmy
助けてくれてありがとう=]
これは私が使用することになったクラスです
class Descriptor
{
public void PrintProperties(object obj)
{
PrintProperties(obj, 0);
}
public void PrintProperties(object obj, int indent)
{
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);
if (propValue.GetType().IsArray)
{
object[] arrary = (object[]) propValue;
foreach (string value in arrary)
{
if (property.PropertyType.Assembly == objType.Assembly)
{
Console.WriteLine("{0}{1}:", indentString, property.Name);
PrintProperties(value, indent + 2);
}
else
{
Console.WriteLine("{0}{1}: {2}", indentString, property.Name, value);
}
}
continue;
}
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);
}
}
}
}
これから、このクラスでLog4Netを使用します。これで、mvc3サイト全体で、ViewModelsが提供および投稿された状態でこれを呼び出して、スイッチをオンにしたときに包括的なデバッグを取得できます。