使用连续的TryParse调用声音的方式来猜测字符串的“真实型”?字符串、声音、真实、方式

2023-09-03 16:40:47 作者:总有刁民想捶朕

这涉及到我的Are有使用T4生成类?问题的任何项目模板。我有一串列表( nvarchar的)参数值,我需要为生成正确类型的类属性。

This relates to my Are there any project templates for using T4 to generate classes? question. I have lists of string (nvarchar) parameter values I need to generate properly typed class properties for.

中的值是所有原始 - 最复杂的幸福的DateTime - 在集合{ INT ,布尔的DateTime }。目前,我有手codeD类型属性一 - 很多 - 这样的名单,并分析我开始与 DateTime.TryParseExact 的字符串。如果失败,我尝试 Double.TryParse ,并在底部我放弃了猜测和假设它确实是一个字符串。

The values are all primitives - the most complex being DateTime - in the set { int, double, bool, DateTime }. Currently I have hand coded typed properties for one - of many - such lists, and to parse the string I start with DateTime.TryParseExact. If that fails, I try Double.TryParse, and at the bottom I give up guessing and assume it really is a string.

这是一个相当完善的方法,还是有其他更复杂的或精确的方法我宁愿用?

Is this a fairly sound approach, or are there other more complicated or accurate methods I should rather use?

推荐答案

如果设定值仅为 [双,日期时间,布尔] 这将是一个详尽的,但比较健全的方法。我们根本的套之间,重叠(总是布尔 5 从来都不是一个布尔)。

If the set of values was only [double, DateTime, bool] this would be an exhaustive but fairly sound method. There is simply so overlap between those sets (true is always a bool and 5 is never a bool).

同时拥有 INT 使这个命题有点片状,因为有大量的重叠。基本上任何 INT 也可以看作是一个。我怎样除preT例如 4 ,如果它出现在值设置?这可能是除preTED两种方式,如果值随时间而改变,你可以看到你产生code更改以及类型。

Having both int and double makes this proposition a bit flaky because there is a large amount of overlap. Essentially any int can be also seen as a double. How am I to interpret for example 4 if it appears in the value set? It could be interpreted both ways and if values change over time you could see the type of your generated code changing as well.

试想,如果一列始终只是巧合了完整的数字。因此,你产生的 INT 值,并写了一点点code这取决于他们是 INT 。然后,在一个月左右后,一个非整数,并将突然你吐出值。这可能会对你的code一个不平凡的影响。

Consider if a column always had whole numbers simply by coincidence. Hence you generated int value and wrote a bit of code that depended on them being int. Then a month or so later a non-whole number was added and suddenly you are spitting out double values. This would probably have a non-trivial affect on your code.

我个人采取的方法是简单地有其规定的内容的类型另一个表。

Personally the approach I would take is to simply have another table which dictated the type of the contents.