1
我有以下通用方法:與對象參數和泛型處理
public static string Glue(string prefix, string value)
{
return String.Format("{0}={1}&", prefix, value);
}
public static string Format<T>(string prefix, T obj) where T : struct
{
return Glue(prefix, (obj).ToString()); ;
}
public static string Format<T>(string prefix, List<T> obj) where T : struct
{
return String.Join("",obj.Select(e => Glue(prefix, e.ToString())).ToArray());
}
現在,我想打電話給他們與進來作爲object
,可能是多種類型的參數。
我開始寫一些代碼,並開始看起來像它的將有一個很長的if/else序列:
// type of value is object, and newPrefix is string
if (value is int)
{
return Format(newPrefix, (int)(value));
}
else if (value is double)
{
return Format(newPrefix, (double)value);
}
...
是否有避免這種長的if/else序列的方法嗎?
好主意!謝謝。 – Candide 2012-03-04 07:42:00