microsoft/teams.net
Publicmirrored fromhttps://github.com/microsoft/teams.netAvailable
Libraries/Microsoft.Teams.Common/StringEnum.cs
66lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | // Licensed under the MIT License. |
| 3 | |
| 4 | using System.Text.Json; |
| 5 | |
| 6 | namespace Microsoft.Teams.Common; |
| 7 | |
| 8 | [System.Text.Json.Serialization.JsonConverter(typeof(JsonConverter<StringEnum>))] |
| 9 | public class StringEnum(string value, bool caseSensitive = true) : ICloneable, IComparable, IComparable<string>, IEquatable<string> |
| 10 | { |
| 11 | public string Value { get; set; } = value; |
| 12 | |
| 13 | private readonly bool _caseSensitive = caseSensitive; |
| 14 | |
| 15 | public object Clone() => new StringEnum(Value); |
| 16 | public int CompareTo(object? value) => Value.CompareTo(value); |
| 17 | public int CompareTo(string? value) => Value.CompareTo(value); |
| 18 | public override string ToString() => Value; |
| 19 | public override int GetHashCode() => Value.GetHashCode(); |
| 20 | public override bool Equals(object? value) => Value.Equals(value); |
| 21 | public bool Equals(StringEnum? value) => Value.Equals(value?.Value); |
| 22 | public bool Equals(string? value) |
| 23 | { |
| 24 | if (!_caseSensitive) |
| 25 | { |
| 26 | return Value.ToLower().Equals(value?.ToLower()); |
| 27 | } |
| 28 | |
| 29 | return Value.Equals(value); |
| 30 | } |
| 31 | |
| 32 | public static bool operator ==(StringEnum? a, StringEnum? b) => a?.Value == b?.Value; |
| 33 | public static bool operator !=(StringEnum? a, StringEnum? b) => a?.Value != b?.Value; |
| 34 | public static implicit operator string(StringEnum value) => value.Value; |
| 35 | |
| 36 | public class JsonConverter<TStringEnum> : System.Text.Json.Serialization.JsonConverter<TStringEnum> |
| 37 | where TStringEnum : StringEnum |
| 38 | { |
| 39 | public override TStringEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| 40 | { |
| 41 | var value = reader.GetString(); |
| 42 | |
| 43 | if (value is null) |
| 44 | { |
| 45 | throw new JsonException("value must not be null"); |
| 46 | } |
| 47 | |
| 48 | var res = Activator.CreateInstance( |
| 49 | typeof(TStringEnum), |
| 50 | [value] |
| 51 | ); |
| 52 | |
| 53 | if (res is null) |
| 54 | { |
| 55 | throw new JsonException($"could not create instance of '{typeof(TStringEnum)}'"); |
| 56 | } |
| 57 | |
| 58 | return (TStringEnum)res; |
| 59 | } |
| 60 | |
| 61 | public override void Write(Utf8JsonWriter writer, TStringEnum value, JsonSerializerOptions options) |
| 62 | { |
| 63 | writer.WriteStringValue(value.Value); |
| 64 | } |
| 65 | } |
| 66 | } |