![](/img/trans.png)
[英]How to implement a method, into interface, with parameter and returned value generic in C#
[英]How to determine the type of the returned value within the generic method
我们创建了一个通用方法,如下所示:
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的类型。
有没有办法做到这一点?
感谢您所有的帮助。 问候。
可以,但是您应该考虑这是否是一个好主意。 你总是可以说
if (typeof(T) == typeof(int)) whatever
但是这样做有点难闻的代码味道。 泛型的全部要点是泛型 。 如果您有用于T为整数的专用代码,那么为什么不简单地添加另一个处理整数情况的方法呢?
当然,只需添加如下代码:
if(typeof(TReturnType) == typeof(int))
{
var number = (int)returnValue;
//Validate your output
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.