0

Obviously this isn't something you would want to do unless you're in a helpless situation, but does anyone have a good example of something like this (bonus points for thinking of a clearer method name):

public static object ConvertToBestGuessPrimitive(string toConvert)
{
    if(looksLikeAnInt)
    {
        return as an int;
    }
    else if(looksLikeABoolean)
    {
        return as a boolean;
    }
    else
    {
        return as a string;
    }
}

The only idea I had was to chain together a bunch of TryParse methods together in a sensible order and fall back to string if nothing works. Can anyone think of something better? This question has probably already been answered somewhere, but I can't seem to find any useful results with the overly generic search terms being used.

Edit - Since there's been some criticism of how useful this would be without an example, here's one I came up with to satisfy a concrete need (however implausible)...Say I am parsing an error log file that I get from an uncontrolled source. The log file has method names and arguments that were provided for where the error occurred. I want to automate testing the error conditions by finding the best matched method and arguments and attempting to call them again. Maybe a stupid example (please don't try and come up with "but you could do this in this scenario" responses since this is just an example), but it illustrates a few points: 1) The input is out of my control. 2) The best-guess is based on some criteria for finding a suitable match. For example: a "10/2/2012" is more likely to mean a DateTime than a string.

4

2 回答 2

1

所以你想摆脱 if-else 吗?像这样的东西怎么样:

interface IConverter
{
  bool TryConvert(string obj, out object result);
}

class IntConvert : IConverter
{
  public bool TryConvert(string obj, out object result) { /* stuff here */ }
}

class BoolConverter : IConverter {...}

// etc.
List<IConverter> converters = new List<IConverter>();
converters.Add(new IntConvert());
converters.Add(new BoolConvert());

public static object ConvertToBestGuessPrimitive(string toConvert)
{
  object obj;
  foreach(var converter in converters) {
    if(converter.TryConvert(toConvert, out obj))
       return obj;
  }

  return null;
}

更新:感谢 Servy 的建议。

于 2013-02-11T15:07:59.910 回答
0

实际上,尝试解析是最合理的方式,因为解析是特定于文化的。如果您只是要求 .NET Framework 进行解析,您将自动遵守当前的文化设置。这与手动解析方法(可能基于正则表达式)形成对比。

另外,我不知道任何字符串可以在 bool、int、float 和 DateTime 之间进行模棱两可的解释。(明显的例外是任何 int 也是浮点数,因此首先解析 int)。

一个更好的名字将是ConvertToBestGuessPrimitiveType。我添加了“类型”。

于 2013-02-11T15:05:09.873 回答