Skip to content

Instantly share code, notes, and snippets.

@121jigowatts
Created May 27, 2015 09:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 121jigowatts/a490d5eeaf0d1c3fcdf8 to your computer and use it in GitHub Desktop.
Save 121jigowatts/a490d5eeaf0d1c3fcdf8 to your computer and use it in GitHub Desktop.
[属性とリフレクション]プロパティに表示用の属性を付与する
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
//データ
var data = new SampleData() { ID = 1, Name = "TEST01", Address = "Tokyo" };
//Text取得
Type t = typeof(SampleData);
Console.WriteLine(t.Name);
PropertyInfo[] properties = t.GetProperties();
foreach (var prop in properties)
{
//AllowMultiple = false のため
//trueの場合はGetCustomAttributesで全て取得できる
Attribute txt = Attribute.GetCustomAttribute(prop, typeof(TextAttribute));
TextAttribute tax = txt as TextAttribute;
Console.WriteLine(prop.Name + " \t-> " + tax.Text + ":" + prop.GetValue(data, null));
}
Console.ReadKey();
}
}
}
namespace ConsoleApplication
{
public class SampleData
{
[Text("キー")]
public int ID { get; set; }
[Text("名前")]
public string Name { get; set; }
[Text("住所")]
public string Address { get; set; }
}
}
using System;
namespace ConsoleApplication
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class TextAttribute : System.Attribute
{
public string Text { get; private set; }
public TextAttribute(string text)
{
this.Text = text;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment