![](/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.