Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Enumに別名?をつけて表示する
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Gender.Female.ToJapanese());
Console.ReadLine();
}
}
public enum Gender
{
[Japanese("不明")]
Unknown,
[Japanese("男性")]
Male,
[Japanese("女性")]
Female
}
public class JapaneseAttribute : Attribute
{
public string Label { get; set; }
public JapaneseAttribute(string label)
{
Label = label;
}
}
public static class GenderExtensions
{
public static string ToJapanese<T>(this T hasJapaneseValue) where T : struct
{
Type type = hasJapaneseValue.GetType();
if (!type.IsEnum)
{
throw new ArgumentException();
}
var memberInfo = type.GetMember(hasJapaneseValue.ToString()).Single();
var attribute = memberInfo.GetCustomAttribute<JapaneseAttribute>();
return attribute?.Label;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment