在编写程序的时候经常会碰到同一个方法有多个重载,其传入传出参数差不多,只是类型不一致。如下所示:
public double GetData(){ }
public string GetData(){ }
public int GetData() { }
对方法进行重载往往显得程序臃肿,那么有没有更好的方法解决呢?
这里我们采用泛型解决,具体代码实现如下:
public static T GetData<T>()
{
Type t = typeof(T);
if(t == typeof(Double))
{
double result = 1.00009;
return (T)(Object)result;
}
else if(t == typeof(string))
{
string result = "这是string类型";
return (T)(Object)result;
}
return default(T);
}
这是测试方法和测试结果
public static void Main(string[] args)
{
string result1 = GetData<string>();
Console.WriteLine(result1); //这是string类型
double result2 = GetData<double>();
Console.WriteLine(result2); //1.00009
Console.ReadKey();
}
当然这个方法除了解决实体参数作为泛型返回的问题外,另一个非常棒的用处是:在调用方法时指定返回值类型,例如Newtonsoft.Json中json对象的反序列化就是这样用的。
List<double> result = Newtonsoft.Json.JsonConvert.DeserializeObject<List<double>>(jsonStr);
参考资料: