Using a special character in Enum, for example. % (C # 3.0)

I have a combo whose source is Enum. Now among other values ​​(e.g. value1, value2

etc.) there is one element Changes(%)that will be displayed in combos.

How to determine the change (%) in the transfer?

Using C # 3.0

thank

+3
source share
4 answers

You can not. Enum value names must be valid C # identifiers. You should not try to put display names there.

Instead, consider decorating each value with an attribute [Description]that you can get with reflection:

public enum ChangeType
{
    [Description("Changes (%)")]
    PercentageChanges,

    [Description("Changes (absolute)")]
    AbsoluteChanges
}

, , . i18n, , , , .

EDIT: .

+8

# , Enum, , , , , "<", " > " "=", .

, , .

0

FWIW... , → → ... Pulling

0

I use the Jon approach (Description attribute for enumerations) along with the extension method below to conveniently find a description:

public static class EnumExtensions
{
  public static T GetAttribute<T>(this Enum enumerationValue) where T : Attribute
  {
    T[] attributes = GetAttributes<T>(enumerationValue);
    return attributes.Length > 0 ? attributes[0] : null;
  }

  public static string GetDescription(this Enum enumerationValue, string descriptionIfNull = "")
  {
    if (enumerationValue != null)
    {
      DescriptionAttribute attribute = enumerationValue.GetAttribute<DescriptionAttribute>();
      return attribute != null ? attribute.Description : enumerationValue.ToString();
    }
    return descriptionIfNull;
  }
}

Usage example:

[TestClass]
public class WhenGettingDescriptionOfAnEnum
{
  private enum SampleEnum
  {
    First,
    [Description("description")]
    Second
  }

  [TestMethod]
  public void ShouldReturnNameOfEnumIfItHasNoDescription()
  {
    SampleEnum.First.GetDescription().Should().Be("First");
  }

  [TestMethod]
  public void ShouldReturnDescriptionIfThereIsOne()
  {
    SampleEnum.Second.GetDescription().Should().Be("description");
  }
}
0
source

Source: https://habr.com/ru/post/1760060/


All Articles