Skip to content

Instantly share code, notes, and snippets.

@nuitsjp
Last active March 13, 2020 21:45
Show Gist options
  • Save nuitsjp/4e871c670c61adcea6598f21b015f908 to your computer and use it in GitHub Desktop.
Save nuitsjp/4e871c670c61adcea6598f21b015f908 to your computer and use it in GitHub Desktop.
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