I am trying to implement a generic method for values that provide Parse
and ParseExact
methods. Types for which my method should work, are value types (like double
, int
etc.) and TimeSpan
.
Any ideas how I can implement what I describe?
To understand better what I need, I made some code that roughly depicts what I would like to achieve (obviously it doesn't work). Flags
is just some enum
.
public Dictionary<Flags, object> FlagValues { get; } = new Dictionary<Flags, object>();
public T GetFlagValue<T>(Flags flag, string formatString = null) where T : struct
{
T result = default(T);
if (FlagValues.TryGetValue(flag, out object flagValueRaw))
{
if (formatString == null)
{
result = T.Parse(flagValueRaw, CultureInfo.InvariantCulture);
}
else
{
result = T.ParseExact(flagValueRaw, formatString, CultureInfo.InvariantCulture);
}
}
return result;
}
CodePudding user response:
// Error handling not included
// Since the first parameter is string in all Parse, ParseExact.
public Dictionary<Flags, string> FlagValues { get; } = new();
public T GetFlagValue<T>(Flags flag, string? formatString = null) where T : struct
{
if (FlagValues.TryGetValue(flag, out var flagValueRaw))
{
if (!string.IsNullOrEmpty(formatString))
{
var parseExact = typeof(T).GetMethod("ParseExact", new[] { typeof(string), typeof(string), typeof(IFormatProvider) });
if (parseExact is not null)
return (T)parseExact.Invoke(null, new object?[] { flagValueRaw, formatString, CultureInfo.InvariantCulture })!;
}
var parse = typeof(T).GetMethod("Parse", new[] { typeof(string), typeof(IFormatProvider) })!;
if (parse is not null)
return (T)parse.Invoke(null, new object?[] { flagValueRaw, CultureInfo.InvariantCulture })!;
}
return default;
}