Last active
March 13, 2020 21:45
-
-
Save nuitsjp/4e871c670c61adcea6598f21b015f908 to your computer and use it in GitHub Desktop.
Enumに別名?をつけて表示する
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
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