4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【C#】クラスのプロパティでループする

Posted at

「プロパティ名 = 値」といったログ出力を行いたかった時に見つけたメソッドです。
便利だったので共有。

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

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?