What is it, naokirin?

属性を使ったフィールドの説明と表示(C#)

今回もまたメモ書き。

なんとなく使ってみようかなぁという感じでC#の属性をはじめて自分で定義して使ってみました。

属性でフィールドに説明をつけられるようにして、クラス内のメソッドで説明とフィールドの値を表示する。
という感じでプログラムを書いてみました。

コードはこんな感じ。

using System;
using System.Reflection;

public class Program
{
    public static void Main(string[] args)
    {
        Sample sample = new Sample(22, 0);

        sample.ShowAttributedFields();
    }
}

// 属性の定義
[AttributeUsage(
    AttributeTargets.Field,
    AllowMultiple = true,
    Inherited = false)]
public class FieldDescriptionAttribute : Attribute
{
    private string description;
    public FieldDescriptionAttribute(string name) { this.description = name; }
    public string Description { get { return this.description; } }
}

public class Sample
{
    [FieldDescription("xの値")]
    private int x;
    public int y;


    public Sample(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    // 属性の定義されたフィールドの説明と値を表示
    public void ShowAttributedFields()
    {
        Type t = typeof(Sample);
        try
        {
            foreach (FieldInfo field in t.GetFields(BindingFlags.NonPublic
                | BindingFlags.Public | BindingFlags.Instance))
            {
                FieldInfoShow(field);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception: {0}", e.Message);
        }
    }

    private void  FieldInfoShow(FieldInfo field)
    {
        Attribute[] names = Attribute.GetCustomAttributes(field, 
            typeof(FieldsDescriptionAttribute));

        if (names.Length != 0)
        {
            foreach (Attribute att in names)
            {
                FieldsDescriptionAttribute name = att as FieldsDescriptionAttribute;

                if (name != null)
                {
                    Console.WriteLine("{0}: {1}", name.Description, 
                        field.GetValue(this).ToString());
                }
            }
        }
    }
}


実行結果としては

xの値: 22

となります。ちなみにSampleクラスのフィールドyは属性がついていないので表示されていません。


単純に実装してみようという感じで実装したので、Sampleクラスが何をしたいクラスなのかよくわからない感じになってしまっています。

C#もやらないとどんどん忘れていく一方なので、こういうことでもいいのでたまにでもやるべきかなとは思いました。