处理对象参数和泛型

时间:2012-03-04 07:20:31

标签: c# generics

我有以下通用方法:

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这么长的序列?

1 个答案:

答案 0 :(得分:2)

如前所述,没有太多方法可以使这更简单。 Format方法仅限于采用在呼叫站点易于检测的值类型(结构)

if (value.GetType().IsValueType) {
  // it's a struct
}

但由于无法提供Format类型,因此无法让T调用满意。

这里你可以做的是稍微改变Format。方法调用仅使用适用于所有类型的ToString方法。您可以删除struct约束,然后使用object表单

中已有的值调用它
public static string Format(string prefix, object obj) {
    return Glue(prefix, obj.ToString()); ;
}

if (value.GetType().IsValueType) {
  Format(newPrefix, value);
}