「プロパティ名 = 値」といったログ出力を行いたかった時に見つけたメソッドです。
便利だったので共有。
object.GetType().GetProperties()
using System;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
Fruit fruit = new Fruit(1, "りんご", true);
PropertyInfo[] properties = fruit.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine("プロパティ名:" + property.Name);
Console.WriteLine(" 型:" + property.PropertyType);
Console.WriteLine(" 値:" + property.GetValue(fruit));
Console.WriteLine("");
}
}
}
public class Fruit
{
public int id { get; set; }
public string name { get; set; }
public bool isOrganic { get; set; }
public Fruit(int id, string name, bool isOrganic)
{
this.id = id;
this.name = name;
this.isOrganic = isOrganic;
}
}
実行結果
プロパティ名:id
型:System.Int32
値:1
プロパティ名:name
型:System.String
値:りんご
プロパティ名:isOrganic
型:System.Boolean
値:True
動作環境
Windows10 22H2 OSビルド 19045.2728
Visual Studio Community 2019
C# 7.3
.NET Framework 4.7.2