在C#中创建一个通用方法 [英] Creating a generic method in C#
问题描述
我试图将一堆类似的方法合并成一个通用的方法。我有几个返回查询字符串值的方法,如果查询字符串不存在或格式不正确,则返回null。如果所有类型都是本地可为空的,那么这很容易,但我必须使用可为空的泛型类型作为整数和日期。
I am trying to combine a bunch of similar methods into a generic method. I have several methods that return the value of a querystring, or null if that querystring does not exist or is not in the correct format. This would be easy enough if all the types were natively nullable, but I have to use the nullable generic type for integers and dates.
这是我现在拥有的。但是,如果数字值无效,它将返回0,并且不幸的是,在我的方案中是有效的值。有人可以帮我吗?
Here's what I have now. However, it will pass back a 0 if a numeric value is invalid, and that unfortunately is a valid value in my scenarios. Can somebody help me out? Thanks!
public static T GetQueryString<T>(string key) where T : IConvertible
{
T result = default(T);
if (String.IsNullOrEmpty(HttpContext.Current.Request.QueryString[key]) == false)
{
string value = HttpContext.Current.Request.QueryString[key];
try
{
result = (T)Convert.ChangeType(value, typeof(T));
}
catch
{
//Could not convert. Pass back default value...
result = default(T);
}
}
return result;
}
推荐答案
如果您指定了默认值返回值,而不是使用默认值(T)?
What if you specified the default value to return, instead of using default(T)?
public static T GetQueryString<T>(string key, T defaultValue) {...}
它使调用变得更简单:
var intValue = GetQueryString("intParm", Int32.MinValue);
var strValue = GetQueryString("strParm", "");
var dtmValue = GetQueryString("dtmPatm", DateTime.Now); // eg use today's date if not specified
缺点是需要魔术值来表示无效/缺失查询字符串值。
The downside being you need magic values to denote invalid/missing querystring values.
这篇关于在C#中创建一个通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!