Created
May 27, 2015 09:31
-
-
Save 121jigowatts/a490d5eeaf0d1c3fcdf8 to your computer and use it in GitHub Desktop.
[属性とリフレクション]プロパティに表示用の属性を付与する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace ConsoleApplication | |
{ | |
public class SampleData | |
{ | |
[Text("キー")] | |
public int ID { get; set; } | |
[Text("名前")] | |
public string Name { get; set; } | |
[Text("住所")] | |
public string Address { get; set; } | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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