简体   繁体   English

Convert.ChangeType() 对字符串值有意义吗?

[英]Does Convert.ChangeType() makes sense with a string value?

I found this great post by @hugoware about parsing values: http://hugoware.net/blog/more-control-when-parsing-values .我发现了@hugoware关于解析值的这篇很棒的帖子: http://hugoware.net/blog/more-control-when-parsing-values I re-used his code sample in a project but now I noticed in the last block (line 154 of his code) he uses the Convert.ChangeType() method as a last attempt to "convert" the value.我在一个项目中重新使用了他的代码示例,但现在我注意到在最后一个块(他的代码的第 154 行)中,他使用 Convert.ChangeType() 方法作为“转换”值的最后一次尝试。

Now I wonder if this makes sense, since we're always starting from a string value and I guess Convert.ChangeType only does casting on value types?现在我想知道这是否有意义,因为我们总是从字符串值开始,我猜 Convert.ChangeType 只对值类型进行强制转换? Does it make sense to try that or will it always fail?尝试这样做有意义还是总是会失败?

If you just want to convert strings, I advice you to use ConvertToString / ConvertFromString如果您只想转换字符串,我建议您使用ConvertToString / ConvertFromString

 TypeConverter converter = TypeDescriptor.GetConverter(type);
 string res = converter.ConvertToString(obj);
 object original = converter.ConvertFromString(res);

-- --

you can use Convert.ChangeType() with strings.您可以将 Convert.ChangeType() 与字符串一起使用。 See the MSDN documentation: ChangeType请参阅 MSDN 文档: ChangeType

From MSDN:来自 MSDN:

string s = "12/12/98";
DateTime dt = (DateTime)Convert.ChangeType(s, typeof(DateTime));

In the above case converting from a string makes sense.在上述情况下,从字符串转换是有意义的。

By using this method I suppose it is possible to extend it even further to cope with non-string values eg通过使用这种方法,我想可以进一步扩展它以处理非字符串值,例如

private static bool _PerformConvert<T,U>( U value, ref T result )
{
    object convert = Convert.ChangeType(value, typeof(U) );
    // Continue ...
}

It might make sense to be able to convert from any value around for example, if you had an interface to a 3rd party dll that provided a numerical representation of an object (it has happened.) you could use the more generic version of the code to convert between the 3rd party representation and another representation that makes more sense to your code.例如,如果您有一个与第三方 dll 的接口,该接口提供了 object 的数字表示(它已经发生),那么能够从任何值进行转换可能是有意义的。您可以使用更通用的代码版本在第 3 方表示和对您的代码更有意义的另一种表示之间进行转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM