为简单值

时间:2015-12-24 13:59:05

标签: c# generics type-conversion

我使用了以下两种扩展方法将传入的字符串转换为我需要的字符串。 (整个通信基于发出的信息类型字符串,由始终已知的其他类型组成。)

public static int ToInt(this string self)
{
  try { return Convert.ToInt32(self); }
  catch { return default(int); }
}

public static double ToInt(this string self)
{
  try { return Convert.ToDouble(self); }
  catch { return default(double); }
}

我刚刚了解到信息流将被扩展并包含其他类型。从长远来看,为每种方法添加新的扩展方法是一种确定的疯狂方法,更不用说代码冗余了。所以我试图让它更通用。

public static T ToType<T>(this string self)
{
  if (typeof(T) == typeof(int))
    try { return Convert.ToInt32(self); }
    catch { return default(int); }
}

但是,编译器存在问题(当然,关于类型)。我已尝试在第一次回归中投射,并在第二次使用提供的类型,但问题仍然存在。

public static T ToType<T>(this string self)
{
  if (typeof(T) == typeof(int))
    try { return (T)Convert.ToInt32(self); }
    catch { return default(T); }
}

可以完成吗?或者我期待这里有一堆非常相似的扩展吗?请记住,因为我总是知道正在服务的类型,所以我只需要覆盖那些,以防万一,完全通用和类型安全的方法是不可能的(或非常“黄瓜”)。

另外,请注意我昨天做过手术,但我还是有点休息,所以答案可能很简单。

1 个答案:

答案 0 :(得分:0)

沿another question's answer行,您可以使用 Convert.ChangeType()方法完成此操作。

public static T Get<T>(this String self)
{
  return (T)Convert.ChangeType(self, typeof(T));
}

或者甚至更复杂的版本,如果转换失败,还会有后备。

public static T Get<T>(this String self, T fallBack = default(T))
{
  try { return (T)Convert.ChangeType(self, typeof(T)); }
  catch { return fallBack; }
}

用法如下。

String source = ...
Guid guid = source.Get<Guid>();
int number = source.Get<int>(42);