最佳答案
Similar to Cast int to enum in C# but my enum is a Generic Type parameter. What is the best way to handle this?
Example:
private T ConvertEnum<T>(int i) where T : struct, IConvertible
{
return (T)i;
}
Generates compiler error Cannot convert type 'int' to 'T'
Full code is as follows, where value can contain the int, or null.
private int? TryParseInt(string value)
{
var i = 0;
if (!int.TryParse(value, out i))
{
return null;
}
return i;
}
private T? TryParseEnum<T>(string value) where T : struct, IConvertible
{
var i = TryParseInt(value);
if (!i.HasValue)
{
return null;
}
return (T)i.Value;
}