Ответ 1
Ну, вы можете сделать это:
public static T Foo<T>(string value)
{
if (typeof(T) == typeof(String))
return (T) (object) value;
if (typeof(T) == typeof(int))
return (T) (object) Int32.Parse(value);
...
}
Это будет включать бокс для типов значений, но он будет работать.
Вы уверены, что это лучше всего сделать как один метод, а не (скажем) общий интерфейс, который может быть реализован разными конвертерами?
В качестве альтернативы вам может понадобиться Dictionary<Type, Delegate>
:
Dictionary<Type, Delegate> converters = new Dictionary<Type, Delegate>
{
{ typeof(string), new Func<string, string>(x => x) }
{ typeof(int), new Func<string, int>(x => int.Parse(x)) },
}
тогда вы будете использовать его следующим образом:
public static T Foo<T>(string value)
{
Delegate converter;
if (converters.TryGetValue(typeof(T), out converter))
{
// We know the delegate will really be of the right type
var strongConverter = (Func<string, T>) converter;
return strongConverter(value);
}
// Oops... no such converter. Throw exception or whatever
}