------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EnumReflectionConsoleApp
{
class Program
{
static void Main(string[] args)
{
foreach (var e in Enum.GetValues(typeof(HogeEnum)) as IEnumerable<HogeEnum>)
{
Console.Out.WriteLine(e.EnumName());
}
Console.In.ReadLine();
}
}
[EnumName("ほげ")]
enum HogeEnum
{
[EnumName("HogeHoge")]
A = 1,
B = 2
}
static class EnumExrentions
{
public static string EnumName(this System.Enum value)
{
var fieldInfo = value.GetType().GetField(value.ToString());
var descriptionAttributes = fieldInfo.GetCustomAttributes(
typeof(EnumNameAttribute), false) as EnumNameAttribute[];
if (descriptionAttributes != null && descriptionAttributes.Length > 0)
return descriptionAttributes[0].Name;
else
return value.ToString();
}
}
[AttributeUsage(AttributeTargets.Enum | AttributeTargets.Field)]
public class EnumNameAttribute : Attribute
{
public EnumNameAttribute(string name)
{
this.Name = name;
}
public string Name { get; }
}
}
---取得処理を汎化させてさせてみました。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EnumReflectionConsoleApp
{
class Program
{
static void Main(string[] args)
{
ShowEnumName<HogeEnum>().All(s => { Console.Out.WriteLine(s); return true; });
//HogeHoge
//B
//が出力される
Console.In.ReadLine();
}
static IEnumerable<string> ShowEnumName<T>() where T : struct {
foreach (var e in Enum.GetValues(typeof(T)) as IEnumerable<T>)
{
yield return (e as System.Enum).EnumName();
}
}
}
[EnumName("ほげ")]
enum HogeEnum
{
[EnumName("HogeHoge")]
A = 1,
B = 2
}
static class EnumExrentions
{
public static string EnumName(this System.Enum value)
{
var fieldInfo = value.GetType().GetField(value.ToString());
var descriptionAttributes = fieldInfo.GetCustomAttributes(
typeof(EnumNameAttribute), false) as EnumNameAttribute[];
if (descriptionAttributes != null && descriptionAttributes.Length > 0)
return descriptionAttributes[0].Name;
else
return value.ToString();
}
}
[AttributeUsage(AttributeTargets.Enum | AttributeTargets.Field)]
public class EnumNameAttribute : Attribute
{
public EnumNameAttribute(string name)
{
this.Name = name;
}
public string Name { get; }
}
}
0 件のコメント:
コメントを投稿