我有一个简单的界面与方法,如
bool TryGetValue(string key, out string value);
bool TryGetValue(string key, out int value);
bool TryGetValue(string key, out double value);
bool TryGetValue(string key, out DateTime value);
// only value types allowed
//with the implementation based on dictionary<string, object>
bool TryGetValue(string key, out string value)
{
object rc;
if ( dict.TryGetValue(key, out rc) )
{
value = rc.ToString();
return true;
}
value = null;
return false;
}
Run Code Online (Sandbox Code Playgroud)
对于泛型来说看起来像一个完美的案例
bool TryGetValue<T>(string key, out T value) where T: ValueType;
Run Code Online (Sandbox Code Playgroud)
除了不能解决func实现,任何人?
更新 - 以下不编译,我想避免创建多个TryGet ... funcs!
bool TryGetValue<T>(string key, out T value)
{
return dict.TryGetValue(key, out value) ;
}
Run Code Online (Sandbox Code Playgroud)
我猜你想要的是这个:
bool TryGetValue<TValue>(string key, out TValue value)
{
object rc;
if (dict.TryGetValue(key, out rc))
{
value = (TValue)rc;
return true;
}
value = default(TValue);
return false;
}
Run Code Online (Sandbox Code Playgroud)
如果它们是错误的类型,它实际上不会转换值 - 它假定System.Object在调用方法TValue时,位于字典中的泛型实例实际上是类型TryGetValue.
如果要将方法限制为仅允许泛型参数的值类型,只需将方法签名更改为:
bool TryGetValue<TValue>(string key, out TValue value) where TValue : struct
Run Code Online (Sandbox Code Playgroud)
注意 - JaredPar得到了第一个答案,但似乎已经删除了他,所以我取消了我的,因为我认为这是OP想要的.对于任何意外的重复,我道歉.
| 归档时间: |
|
| 查看次数: |
652 次 |
| 最近记录: |