Go-c# Let the enumeration return a string

Source: Internet
Author: User

The following is a way to return a string using a tag to an enumeration

Each of the following defines an attribute class, and an enumeration helper class

[CSharp]View Plaincopyprint?
  1. [AttributeUsage (attributetargets.field,allowmultiple = false)]
  2. Public sealed class Enumdescriptionattribute:attribute
  3. {
  4. private string description;
  5. public string Description { get { return Description;}}
  6. Public Enumdescriptionattribute (string description)
  7. : base ()
  8. {
  9. this.description = description;
  10. }
  11. }
[CSharp]View Plaincopyprint?
  1. Public static class Enumhelper
  2. {
  3. public static string getdescription (Enum value)
  4. {
  5. if (value = = null)
  6. {
  7. throw New ArgumentException ("value");
  8. }
  9. string description = value.  ToString ();
  10. var fieldInfo = value. GetType (). GetField (description);
  11. var attributes =
  12. (enumdescriptionattribute[]) fieldinfo.getcustomattributes (typeof (Enumdescriptionattribute), false);
  13. if (attributes ! = null && attributes. Length > 0)
  14. {
  15. Description = Attributes[0]. Description;
  16. }
  17. return description;
  18. }
  19. }

Examples of Use:

[CSharp]View Plaincopyprint?
    1. Enum Week
    2. {
    3. [Enumdescription ("Monday")]
    4. Monday,
    5. [Enumdescription ("Tuesday")]
    6. Tuesday
    7. }
    8. The following prints the result: Monday
    9. Console.WriteLine (Enuhelper.getdescription (Week.monday))

Go-c# Let the enumeration return a string

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.