【发布时间】:2021-02-05 22:58:43
【问题描述】:
我有这两种方法:
private int GetInt(string key)
{
try
{
return (int)_data[key];
} catch (KeyNotFoundException)
{
return 0;
}
}
private int? GetNullableInt(string key)
{
try
{
return (int?)_data[key];
} catch (KeyNotFoundException)
{
return null;
}
}
但是,我想创建一种通用方法,以防止代码重复,类似于:
private T Get<T>(string key, T type)
{
try
{
return (T)_data[key];
} catch (KeyNotFoundException)
{
return default(T);
}
}
但是,我似乎没有做对。该方法可以编译,但我不知道如何调用它:
Get("myKey", typeof(int));
没用。
Get("myKey", int);
这将是我的偏好,但这似乎是无效的语法。
【问题讨论】:
-
你已经接近了。
private T Get<T>(string key),并称之为Get<int>("key") -
如果
_data是IDictionary<,>你真的应该使用TryGetValue -
@xanatos 谢谢。使用泛型,这意味着只有一个地方可以更改代码:)
-
@canton7 听起来像是对我的回答!
-
这几乎可以肯定是一个重复,但这是一个非常基本的问题,我很难找到任何东西......