我想为一些类型设置泛型函数,例如long,TimeSpan和DateTime.
public static T Parse<T>(string text)
{
T store;
if(typeof(T) == typeof(TimeSpan)
store = (T)((object) new TimeSpan(0, 1, 0));
else
{
T.tryParse(text, out store);
}
return store;
}
Run Code Online (Sandbox Code Playgroud)
有没有比双T /对象演员更好的方法?
t.tryParse没有编译,我怎样才能完成类似的东西呢?
在我看来,在这种情况下使用重载方法会更好.关于召唤没有什么通用的TryParse- 这Int32.TryParse是一种完全不同的方法Int64.TryParse等等.这也会让你远离双重演员(我同意这很难看,但遗憾的是很难避免).这也意味着您要指定哪些类型可以真正支持.
一种选择是使用Dictionary<Type, Func<string, object>>:
// Add some error checking, obviously :)
Func<string, object> parser = parsers[typeof(T)];
return (T) parser(form.Text);
Run Code Online (Sandbox Code Playgroud)
然后用以下内容设置字典:
static readonly Dictionary<Type, Func<string, object>> parsers =
new Dictionary<Type, Func<string, object>>()
{
{ typeof(int), x => int.Parse(x) },
{ typeof(TimeSpan) x => new TimeSpan(0, 1, 0) },
...
}
Run Code Online (Sandbox Code Playgroud)
如果要使用TryParse而不是Parse,则需要创建自己的委托类型,因为使用了out参数(Func/ 中不支持Action).那时的生活变得有点困难.
顺便说一下,为什么使用out参数而不是返回值?