In my opinion, it is useful to use the AbstractDataType template wherever the general value is used with specific intentions (this case was made by many others with examples such as Percentage, ReadonlyString, ConnectionString, etc.)
Please note that I personally believe that with and from implicit conversions like all this is empty (having an implicit transform, there is no longer a compiler to guarantee that common values ββare used with a specific intent in the right place).
Here is a pattern that should inspire you to be your own: you can still choose the level of convenience / verbosity that you prefer. He shows two approaches:
- _byInt index PseudoInt dictionary
- _byEnum indexes a dictionary by type Enum: int
Notes
- If you are #define IMPLICIT_CONVERSIONS, you will get implicit conversions to the base index type (so that int or enumerate)
- this is extrapolated to all types of values, including user-defined ones (try it with the XYZCoord structure :))
- see if you really need conversions to and from Enum types
Without further ado:
#define IMPLICIT_CONVERSIONS using System.Collections.Generic; namespace NS { public enum PositionEnum : int { Begin = 0, Normal = 1, End = 99 } public struct Pseudo<T> where T : struct { public T Value; public Pseudo(T value) { Value = value; } #if IMPLICIT_CONVERSIONS public static implicit operator T(Pseudo<T> pi) { return pi.Value; } public static implicit operator Pseudo<T>(T ni) { return new Pseudo<T>(ni); } #endif } static class Program { private static Pseudo<T> AsPseudo<T>(this T value) where T : struct { return new Pseudo<T>(value); } private static readonly IDictionary<Pseudo<int>, string> _byInt = new Dictionary<Pseudo<int>, string>() { { 0, "aap" }, { 1, "noot" }, { 99, "mies" }, }; private static readonly IDictionary<Pseudo<PositionEnum>, string> _byEnum = new Dictionary<Pseudo<PositionEnum>, string>() { { PositionEnum.Begin, "aap" }, { PositionEnum.Normal, "noot" }, { PositionEnum.End, "mies" }, }; public static void Main(string[] args) { string s; s = _byInt[0]; s = _byEnum[PositionEnum.Normal]; } } }
sehe
source share