简体   繁体   English

如何确定泛型方法中返回值的类型

[英]How to determine the type of the returned value within the generic method

We've created a generic method like so: 我们创建了一个通用方法,如下所示:

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;
}

Now, we would like to put some error handling in this method so that in case we're expecting a numeric type we can do, for example, an int.TryParse(returnValue, out myNewInt). 现在,我们想在此方法中进行一些错误处理,以防万一我们期望使用数值类型,例如int.TryParse(returnValue,out myNewInt)。 Of course to be able to do that we would have to be able to determine the type of TReturnType within the method. 当然,要做到这一点,我们必须能够确定方法中TReturnType的类型。

Is there a way to do this? 有没有办法做到这一点?

Thanks for all of your help. 感谢您所有的帮助。 Regards. 问候。

Sure, but you should consider whether or not this is a good idea. 可以,但是您应该考虑这是否是一个好主意。 You can always say 你总是可以说

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

But doing so is a bit of a bad code smell. 但是这样做有点难闻的代码味道。 The whole point of generics is to be generic . 泛型的全部要点是泛型 If you have special-purpose code for when T is an integer, then why not simply add another method that handles exactly the integer case? 如果您有用于T为整数的专用代码,那么为什么不简单地添加另一个处理整数情况的方法呢?

Sure, just add in some code like this: 当然,只需添加如下代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM