2009-07-10 48 views
0

我们已经创建了一个通用的方法,像这样内确定返回值的类型:如何泛型方法

 
public TReturnType GetValue(string key) 
{ 
    var configurationParameter = (from cp in _repository.ConfigurationParameters 
     where cp.ConfigurationParameterKey == key 
     select cp).FirstOrDefault(); 

    var returnValue (TReturnType)Convert.ChangeType(configurationParameter.ConfigurationParameterValue, typeof (TReturnType)); 
    return returnValue; 
} 

现在,我们希望把一些错误的这种方法处理,这样的情况下,我们期待着一个我们可以做的数字类型,例如,一个int.TryParse(returnValue,out myNewInt)。当然,要做到这一点,我们必须能够确定方法内的TReturnType类型。

有没有办法做到这一点?

感谢您的帮助。 此致敬礼。

回答

2

当然,只添加一些像这样的代码:

if(typeof(TReturnType) == typeof(int)) 
{ 
    var number = (int)returnValue; 
    //Validate your output 
} 
+0

哦,我的天啊!这太简单了,绝对让人尴尬。我现在肯定需要回家。 谢谢。 – 2009-07-10 20:46:50

3

当然,但你应该考虑这是否是一个好主意。你总是可以说

if (typeof(T) == typeof(int)) whatever 

但是这样做有点不好的代码味道。泛型的整点是是通用的。如果你有特殊用途代码为T时是一个整数,那么为什么不简单地增加另一个方法来处理完整的大小写?

+0

我在一个支持3种ID的泛型集合上做了这个:字符串,整数和GUID。其他任何东西都会抛出一个未实现的异常。 – 2009-07-10 20:36:59